python - 如何使用静态方法初始化静态变量?

标签 python static

class One:
    i = One.get(9)
    @staticmethod
    def get(val):
        pass

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

NameError: name 'One' is not defined

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

最佳答案

class One:
    @staticmethod
    def get(val):
        pass

    i = get.__func__(9)

但这可能不是最Pythonic的方式。请注意 i变量位于 get 声明之后。自 @staticmethod不可直接调用(如果这样做,您将收到一条消息),您必须执行底层函数( __func__ )。

关于python - 如何使用静态方法初始化静态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020795/

相关文章:

java - 错误 : field name cannot be declared static

java - 与其他 "service"类相比,使用所有静态方法的缺点是什么?

python - 如何使我的Discord机器人播放YouTube上的音频

swift - 我可以直接从协议(protocol)扩展类型访问默认静态变量吗?

c++ - 程序终止后 C++ const static 的行为

c# - 连接 Program.cs 和 Form.cs

python - 将元组扩展为参数

python - 根据多组索引对二维张量的列求和

python - 获取 NumPy Vector 中递增组的开始和停止值

python - 在 PySpark 中转置 RowMatrix