相关疑难解决方法(0)

`classmethod` 和元类方法有什么区别?

在 Python 中,我可以使用@classmethod装饰器创建一个类方法:

>>> class C:
...     @classmethod
...     def f(cls):
...             print(f'f called with cls={cls}')
...
>>> C.f()
f called with cls=<class '__main__.C'>
Run Code Online (Sandbox Code Playgroud)

或者,我可以在元类上使用普通(实例)方法:

>>> class M(type):
...     def f(cls):
...             print(f'f called with cls={cls}')
...
>>> class C(metaclass=M):
...     pass
...
>>> C.f()
f called with cls=<class '__main__.C'>
Run Code Online (Sandbox Code Playgroud)

如 的输出所示C.f(),这两种方法提供了相似的功能。

@classmethod在元类上使用和使用普通方法有什么区别?

python methods metaclass class-method

14
推荐指数
1
解决办法
633
查看次数

标签 统计

class-method ×1

metaclass ×1

methods ×1

python ×1