【问题标题】:How to initialise static variable using static method? [duplicate]如何使用静态方法初始化静态变量? [复制]
【发布时间】:2016-03-05 09:34:22
【问题描述】:
class One:
    i = One.get(9)
    @staticmethod
    def get(val):
        pass

我尝试使用静态方法初始化静态变量,但是上面的代码引发了这个错误:

NameError: name 'One' is not defined

如何在 Python 中使用静态方法初始化静态变量?

【问题讨论】:

    标签: python static


    【解决方案1】:
    class One:
        @staticmethod
        def get(val):
            pass
    
        i = get.__func__(9)
    

    虽然可能不是最 Pythonic 的方式。注意i 变量在get 的声明之后。由于@staticmethod 不能直接调用(如果这样做,您会收到一条消息),因此您必须改为执行底层函数(__func__)。

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 2019-04-15
      • 2011-08-22
      • 2010-12-22
      • 2017-05-13
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多