English documents:
staticmethod(function)
Return a static method for function.
A static method does not receive an implicit first argument.
< span class= "n" > 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 (such as C.f() ) or on an instance (such as C().f() ). The instance is ignored except for its class.
Description
1. function function when a function is changed into a static method of the class.
>>>classStudent (object):def __init__(self,name): Self.name=namedefSayHello (lang):Print(Lang)ifLang = ='en': Print('welcome!') Else: Print('Hi there! ') Staticmethod (SayHello)>>>Student.sayhello<function Student.sayhello at 0x02ac7810>>>> a = Student ('Bob')>>>A.sayhello<bound Method Student.sayhello of <__main__. Student Object at 0x02ad03f0>>
2. A static method can be called by a class, or it can be called by an instance object of a class.
>>> Student.sayhello ('en'# class is called, the ' en ' is passed to the lang parameter enwelcome! # when the class instance object is called, the object itself is passed to the lang parameter <__main__. Student object at 0x02ad03f0> Hello!
3. To define a method as a static method of a class, the correct method is to use the@staticmethod装饰器,这样在实例对象调用的时候,不会把实例对象本身传入静态方法的第一个参数了。
#defining static methods with Adorners>>>classStudent (object):def __init__(self,name): Self.name=name @staticmethoddefSayHello (lang):Print(Lang)ifLang = ='en': Print('welcome!') Else: Print('Hi there! ') >>> Student.sayhello ('en')#class call, ' en ' passed to the lang parameterenwelcome!>>> B = Student ('Kim')#class instance object is called, and the class instance object is no longer passed into the static method>>>B.sayhello () Traceback (most recent): File"<pyshell#71>", Line 1,inch<module>B.sayhello () Typeerror:sayhello () Missing1 Required positional argument:'Lang'>>> B.sayhello ('ZH')#class instance object called, ' zh ' passed to the lang parameterZH Hello!
Python built-in function (--classmethod)