About static methods for classes: @staticmethod and @classmethod
1, use these two methods, do not instantiate class, directly can be used, such as: Stu.say ()
2, the difference between the two methods:
1, @staticmethod do not need to add parameters;
Call class variable with: Class name. class variable name;
Call class function with: Class name. function ()
2, @classmethod need to add parameter cls;
Call class variables with: CLS. class variable name;
Call a class function with: CLS (). function ()
classStu (object): Country=' China' #class Variables def __init__(Self, name=' World'): Self.name=name @staticmethod#The static method, which has nothing to do with the class itself, is equivalent to defining a method within the class . defsay ():Print('Shanghai') Print(stu.country) Stu ('Static'). Hi () @classmethod#The static method, unlike the class method, is that it can use a class variable and must pass a value that represents the class defHello (CLS):Print('-------------------------') Print(Cls.country) Cls.say () CLS (). Hi ()defhi (self):#This is an example method . Print(Self.name) Stu.say () Stu.hello ()#t = Stu (' name ')#T.hi ()#T.say ()#T.hello ()
Python static Method-class method