Home > database >  use current class without self in python (static method inherit) [duplicate]
use current class without self in python (static method inherit) [duplicate]

Time:09-18

I wondering if there is way to let static method use variable in current class. With that, I can change class action by change member in it.

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]

CodePudding user response:

What your looking for is called a class method, with the syntax:

class A:

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

Using this decorator the class iself is passed into the function, the cls variable is not a class instance. This produces the results you were looking for

CodePudding user response:

For that purpose, there is @classmethod. Every classmethod has an implicit argument that receives the class, often named simply cls.

Your method can be transformed in following way:

    @classmethod
    def static_function(cls):
        print(cls.var, cls.lst)
  • Related