对象没有属性。 python中的新类

时间:2016-06-16 23:48:17

标签: python class

import praw
import time

class getPms():

    r = praw.Reddit(user_agent="Test Bot By /u/TheC4T")
    r.login(username='*************', password='***************')

    cache = []
    inboxMessage = []
    file = 'cache.txt'

    def __init__(self):
        cache = self.cacheRead(self, self.file)
        self.bot_run(self)
        self.cacheSave(self, self.file)
        time.sleep(5)
        return self.inboxMessage

    def getPms(self):
        def bot_run():
            inbox = self.r.get_inbox(limit=25)
            print(self.cache)
            # print(r.get_friends())#this works
            for message in inbox:
                if message.id not in self.cache:
                    # print(message.id)
                    print(message.body)
                    # print(message.subject)
                    self.cache.append(message.id)
                    self.inboxMessage.append(message.body)
                    # else:
                    # print("no messages")

        def cacheSave(self, file):
            with open(file, 'w') as f:
                for s in self.cache:
                    f.write(s + '\n')

        def cacheRead(self, file):
            with open(file, 'r') as f:
                cache1 = [line.rstrip('\n') for line in f]
            return cache1

        # while True: #threading is needed in order to run this as a loop. Probably gonna do this in the main method though


    # def getInbox(self):
    #     return self.inboxMessage

例外是:

  cache = self.cacheRead(self, self.file)
AttributeError: 'getPms' object has no attribute 'cacheRead'

我是新手使用python中的类,如果你需要我可以添加的更多信息,需要帮助解决我的错误。它适用于所有功能,但现在我试图将其切换到已停止工作的类。

2 个答案:

答案 0 :(得分:3)

您的cacheRead函数(以及bot_runcacheSave)缩进太多,因此它在您的其他函数getPms的正文中定义。因此,它只能在getPms内访问。但是你试图从__init__调用它。

我不确定你在这里想要实现什么,因为getPms除了三个函数定义之外没有其他内容。据我所知,你应该取出def getPms行并取消它所包含的三个函数,以便它们与__init__方法对齐。

答案 1 :(得分:0)

以下几点:

  1. 除非您明确继承某些特定类,否则可以省略括号:
  2. class A(object):class A():class A:是等效的。

    1. 您的班级名称和班级方法具有相同的名称。我不确定Python是否会对此感到困惑,但你可能会这样做。例如,您可以为自己的班级PMS和方法get命名,这样您就可以获得PMS.get(...)

    2. 在当前版本的缩进cacheReadcacheSave函数中,init无法访问;为什么不把它们移到泛型类命名空间?

    3. 调用成员函数时,您不需要指定self作为第一个参数,因为您已经从此对象调用了该函数。因此,不必像cache = self.cacheRead(self, self.file)那样执行此操作:cache = self.cacheRead(self.file)

相关问题