python - 在设置类属性时引用方法

标签 python class static-methods

class Something(object):
    our_random = Something.random_thing

    @staticmethod
    def random_thing():
         return 4

当然,这是行不通的,因为当我试图调用它的方法时,Something 并不存在。这也不是:

class Something(object):
    our_random = random_thing

    @staticmethod
    def random_thing():
         return 4

我已经通过将 random_thing() 的定义放在类之上来“解决”了这个问题,但我发现这很困惑。

最佳答案

然后在 .__init__() 初始化器中调用它:

class Something(object):
    def __init__(self):
        self.our_random = Something.random_thing()

或者在定义静态方法之后调用它,但仍在定义类;因为它是一个静态方法,所以您必须通过 __func__ 属性访问它:

class Something(object):
    @staticmethod
    def random_thing():
        return 4

    our_random = random_thing.__func__()

如果您不想调用它,只需使用不同的名称创建该方法的副本,只需在定义它之后执行即可:

class Something(object):
    @staticmethod
    def random_thing():
        return 4

    our_random = random_thing   # our_random as an alias for random_thing

类主体作为函数执行,函数的局部命名空间形成类属性。因此,就像函数一样,如果您想引用其他对象,您需要先确保它们已被定义。

关于python - 在设置类属性时引用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865970/

相关文章:

python - 从字典创建 .txt 文件

python - 使用 Python 2.x 中的 'is' 运算符将对象与空元组进行比较

python - 在 Python 中访问非全局变量

c++ - 基于 SDL 的汉诺塔游戏中的奇怪问题

python - SQLAlchemy - 多个类,相同的表

c# - C# 中的静态方法?

C++静态成员函数重载继承

Java找不到公共(public)静态方法

python - Python __setitem__ 使用多个键时发生奇怪的事情

java - 在整个应用程序中检查互联网连接的最佳方式