decorator

Glossary — Python 3.6.3 documentation https://docs.python.org/3/glossary.html

decorator

A function returning another function, usually applied as a function transformation using the ​​@wrapper​​ syntax. Common examples for decorators are ​​classmethod()​​ and ​​staticmethod()​​.

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

 

公司的员工是一个类,每实例化一个员工类,公司人数+1,Python中是通过classmethod 实现 

追问 如果 员工数目 达到123 就禁止实例化员工类 说说 实现思路

 

​@​​​​classmethod​

Transform a method into a class method.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:




class C:
@classmethod
def f(cls, arg1, arg2, ...): ...


The ​​@classmethod​​ 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. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see ​​staticmethod()​​ in this section.

For more information on class methods, consult the documentation on the standard type hierarchy in ​​The standard type hierarchy​​.

 

​@​​​​staticmethod​

Transform a method into a static method.

A static method does not receive an implicit first argument. To declare a static method, use this idiom:




class C:
@staticmethod
def f(arg1, arg2, ...): ...


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.

Static methods in Python are similar to those found in Java or C++. Also see ​​classmethod()​​ for a variant that is useful for creating alternate class constructors.

Like all decorators, it is also possible to call ​​staticmethod​​ as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:

class C: builtin_open = staticmethod(open)

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

 

 

Difference between @staticmethod and @classmethod in Python - Python Central