Python built-in functions (60) -- classmethod, pythonclassmethod
English document:
staticmethod
(Function)
Return a static methodFunction.
A static method does not receive an implicit first argument.
The@staticmethod
Form is a function decorator-see the description of function definitions in Function definitions for details.
It can be called either on the class (suchC.f()
) Or on an instance (suchC().f()
). The instance is ignored before t for its class.
Note:
1. When a function is used, a function is converted into a static method of the class.
>>> Class Student (object): def _ init _ (self, name): self. name = name def sayHello (lang): print (lang) if lang = 'en': print ('Welcome! ') Else: print ('Hello! ') Staticmethod (sayHello) >>> Student. sayHello <function Student. sayHello at 0x02AC7810 >>> a = Student ('bob') >>>. sayHello <bound method Student. sayHello of <__ main __. student object at 0x02AD03F0>
2. Static methods can be called by class or instance objects of class.
>>> Student. sayHello ('en') # When the class is called, The 'en' is passed to the lang parameter enWelcome! >>> A. sayHello () # When calling a class instance object, the object itself is passed to the lang parameter <__main _. Student object at 0x02AD03F0> hello!
3. Define a method as a static method of the class. The correct method is to use@ Staticmethod: in this way, when an instance object is called, The instance object itself is not passed into the first parameter of the static method.
# Use the decorator to define static methods> class Student (object): def _ init _ (self, name): self. name = name @ staticmethod def sayHello (lang): print (lang) if lang = 'en': print ('Welcome! ') Else: print ('Hello! ') >>> Student. sayHello ('en') # class call, 'en' is passed to the lang parameter enWelcome! >>> B = Student ('Kim ') # class instance object call, no longer passing class instance object to static method >>> B. sayHello () Traceback (most recent call last): File "<pyshell #71>", line 1, in <module> B. sayHello () TypeError: sayHello () missing 1 required positional argument: 'lang '>>> B. sayHello ('zh ') # class instance object call, 'zh' is passed to the lang parameter zh hello!