对于静态方法,将自己称为 "this class"; python

refer to self as "this class" for staticmethods; python

我正在尝试构建用于测试的 ETL 机器。

class TestETLMachine(object):

    API_URL = 'https://9g9xhayrh5.execute-api.us-west-2.amazonaws.com/test/data'

    @staticmethod
    def get_email_data(cls):
        headers = {'accept': 'application/json'}
        r = requests.get(cls.API_URL, headers=headers)
        email_objects_as_list_of_dicts = json.loads(r.content)['data']
        return email_objects_as_list_of_dicts

    @staticmethod
    def get_distinct_emails(cls):
        email_data = cls.get_email_data()
        print email_data

for get_distinct_emails 我想给 TestETLMachine.get_email_data() 打电话让它知道我指的是这个 class。这个对象是一个静态机器,这意味着它总是做同样的事情,并且创建它的实例是没有意义的,而且看起来很糟糕。当我现在通过 cls 尝试调用 get_email_data 时,我不能再调用了:

In [9]: TestETLMachine.get_email_data()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-cf48fc1a9c1d> in <module>()
----> 1 TestETLMachine.get_email_data()

TypeError: get_email_data() takes exactly 1 argument (0 given)

如何调用这些 class 方法并在我的下一个 class 方法中使用其他 class 方法?萨拉马特

您正在寻找 classmethod,而不是 staticmethod。如果你用 @classmethod 修饰一个方法,它将隐式接收 class 作为第一个参数。

另见相关问题Meaning of @classmethod and @staticmethod for beginner?