The method of decorating is changed into a static method by @staticmethod Adorner, what is static method? In fact, it is not difficult to understand, the ordinary method can be called directly after instantiation, And in the method can pass self. Invokes an instance variable or a class variable, but a static method cannot access an instance variable or a class variable, and a method that cannot access an instance variable or a class variable is, in fact, nothing to do with the class itself, and its only association with a class is the need to call this method through the class name
classDog (object):def __init__(self,name): Self.name=name @staticmethod#Actually, it's nothing to do with classes . defeat (self,):Print("%s is eating%s"% ('DDD','DD')) d= Dog ("Jianlin") d.eat ()
The above code execution will cause an error
It is said that eat needs a self parameter, but it is not passed when it is called, yes, when eat becomes a static method, the instance itself is not automatically passed as a parameter when it is called by the instance.
Traceback (most recent): " c:/users/administrator.qh-20170325tnqr/pycharmprojects/sssss/ss/day7/static method 1.py " in <module> 'self'
After becoming a static method, it has nothing to do with the class, equivalent to a separate function just the next function of the class
There are two ways to make the above code work correctly
1. When invoked, the instance itself is passed to the Eat method, i.e. D.eat (d)
2. Remove the self parameter in the Eat method, but this also means that you cannot pass self in eat. Calls to other variables in the instance
Method One
classDog (object):def __init__(self,name): Self.name=name @staticmethod#Actually, it's nothing to do with classes . defeat ():Print("%s is eating%s"% ('Mike','steamed Bun')) d= Dog ("Jianlin") d.eat ()#Mike is eating bun
Method Two
classDog (object):def __init__(self,name): Self.name=name @staticmethod#Actually, it's nothing to do with classes . defeat (self,):Print("%s is eating%s"% (Self.name,'steamed Bun')) d= Dog ("Jianlin") D.eat (d)#Jianlin is eating bun
It is best to call static methods with classes to save memory
class Foo (object): # It is best to call static methods with classes to save memory @staticmethod def F1 (ARGS1, ARGS2): print(ARGS1, ARGS2) FOO.F1 (123, 345) # class calls static method execution # 123 345
Python class Advanced Syntax static method