【问题标题】:refer to self as "this class" for staticmethods; python对于静态方法,将 self 称为“此类”; Python
【发布时间】:2016-03-05 16:17:45
【问题描述】:

我正在尝试构建一个 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

对于get_distinct_emails,我想打电话给TestETLMachine.get_email_data(),让它知道我指的是这个类。这个对象是一个静态机器,这意味着它总是做同样的事情,并且创建它的实例是没有意义的并且看起来很糟糕。当我通过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)

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

【问题讨论】:

  • 除非这是一个大大简化的例子,否则我怀疑你根本不需要一个类。 API_URL 仅用于一种方法,cls 仅用于访问该变量。对 url 进行硬编码,或者将其作为 get_email_data 的参数,然后您只剩下两个普通函数 get_email_data(url='https://...')get_distinct_emails(调用 get_email_data)。
  • 这只是一个开始,这是一个 5 部分测试

标签: python class python-3.x static-methods


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2020-03-03
    • 1970-01-01
    • 2015-07-14
    • 2013-01-29
    相关资源
    最近更新 更多