Python - 无法调用仅传递self参数的方法

时间:2014-01-29 21:17:41

标签: python

在python 2.7下。

如何处理那些只传递一个参数的方法,即“自我”?

class MyTwitterClass(object):
    ...
    def keys(self):
        return {
            'consumer_key': self.read_settings().get('Keys', 'consumer_key'),
            "consumer_secret": self.read_settings().get('Keys', 'consumer_secret'),
            "access_token_key": self.read_settings().get('Keys', 'access_token_key'),
            "access_token_secret": self.read_settings().get('Keys', 'access_token_secret')
        }

    api = twitter.Api(consumer_key=keys()['consumer_key'],
                      consumer_secret=keys()['consumer_secret'],
                      access_token_key=keys()['access_token_key'],
                      access_token_secret=keys()['access_token_secret'])

我得到的错误是:

Traceback (most recent call):
    File "..." ...
    ...
     api = twitter.Api(consumer_key=keys()['consumer_key'],
    TypeError: keys() takes exactly 1 argument (0 given)

欢迎任何想法。

2 个答案:

答案 0 :(得分:5)

keys()是您班级的一种方法。要自动传递self参数,您必须以这种方式调用它:

c = MyTwitterClass()
keys = c.keys()

因此,我建议您在班级中添加get_api()方法:

class MyTwitterClass(object):
    ...
    def keys(self):
        return {
            'consumer_key': self.read_settings().get('Keys', 'consumer_key'),
            "consumer_secret": self.read_settings().get('Keys', 'consumer_secret'),
            "access_token_key": self.read_settings().get('Keys', 'access_token_key'),
            "access_token_secret": self.read_settings().get('Keys', 'access_token_secret')
        }

    def get_api(self):
        keys = self.keys() # self refer to the current instance of your class
        api = twitter.Api(consumer_key=keys['consumer_key'],
                          consumer_secret=keys['consumer_secret'],
                          access_token_key=keys['access_token_key'],
                          access_token_secret=keys['access_token_secret'])

        return api

# Now, you can do :

c = MyTwitterClass()
api = c.get_api()

答案 1 :(得分:0)

您需要调用实例方法。 keys()是一种方法,您可以在每个MyTwitterClass对象上调用该方法,如果您在类中,则可以调用self

obj = MyTwitterClass()
[...]
api = twitter.Api(consumer_key=obj.keys()['consumer_key'],
                  consumer_secret=obj.keys()['consumer_secret'],
                  access_token_key=obj.keys()['access_token_key'],
                  access_token_secret=obj.keys()['access_token_secret'])
                                      ^^^^
                                     note this addition