首页 > 解决方案 > 在python中使用没有self的当前类(静态方法继承)

问题描述

我想知道是否有办法让静态方法在当前类中使用变量。这样,我可以通过更改其中的成员来更改集体诉讼。

class A:
    var = 0
    lst = [100, 200, 300]

    @staticmethod
    def static_function():
        print(A.var, A.lst)  # need to indicate current class rather than specific one

    def class_function(self):
        print(self.__class__.var, self.__class__.lst)


class B(A):
    var = 9
    lst = [999, 999, 999]


if __name__ == '__main__':
    B.static_function()   # 0 [100, 200, 300]
    B().class_function()  # 9 [999, 999, 999]
    
    B.static_function()   # what I want: 9 [999, 999, 999]

标签: pythoninheritancestatic-methods

解决方案


您要查找的内容称为类方法,其语法为:

class A:

    @classmethod
    def class_function(cls):
        print(cls.var, cls.lst)

使用这个装饰器,类本身被传递到函数中,cls变量不是类实例。这会产生您正在寻找的结果


推荐阅读