classmethod 封装函数为类方法
内置函数(类)classmethod,Python 官方文档描述如下:
help(classmethod)
Help on class classmethod in module builtins:
class classmethod(object)
| classmethod(function) -> method
|
| Convert a function to be 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, ...):
| ...
|
把一个函数封装成类方法。一个类方法把类自己作为第一个实参,就像一个实例方法把实例自己作为第一个实参。
可将函数作为参数来声明类方法,但请用习惯的装饰器形式(@classmethod)来声明类方法。
type(classmethod)
type
class A:
print_itself = classmethod(print)
A.print_itself()
<class '__main__.A'>
class A:
@classmethod
def print_itself(cls):
print(cls)
A.print_itself()
<class '__main__.A'>