类方法和元类方法之间有什么区别?

问题描述 投票:4回答:1

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

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

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

>>> 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'>

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

在元类上使用@classmethod与使用常规方法有什么区别?

python methods metaclass class-method
1个回答
0
投票

在您的示例中,区别将是其他一些将M设置为其元类的类。

class M(type):
    def f(cls):
        pass

class C(metaclass=M):
    pass

class C2(metaclass=M):
    pass

C.f()
C2.f()
class M(type):
     pass

class C(metaclass=M):
     @classmethod
     def f(cls):
        pass

class C2(metaclass=M):
    pass

C.f()
# C2 does not have 'f'

这里有更多关于元类的信息What are some (concrete) use-cases for metaclasses?

© www.soinside.com 2019 - 2024. All rights reserved.