问题描述
我们如何才能使一个关于谁被欺骗的谎言的阶级呢?
How can we make a class who lies about who he has subclassed?
阅读文档我已经尝试过了:
>>> class AllYourBase(type):
... @classmethod
... def __subclasscheck__(cls, other):
... return True
...
>>> class AllYour(object):
... __metaclass__ = AllYourBase
现在,这堂课应该报告您所有的基地都属于他.
Now, this class should report that all your base are belong to him.
但这没用:
>>> issubclass(AllYour, int)
False
为什么不呢?
推荐答案
如果您希望AllYour
声明自己是每个类的子类,则不可能. __subclasscheck__
在另一个方向上起作用.
If you want AllYour
to claim to be a subclass of every class, that isn't possible. __subclasscheck__
works in the other direction.
如果要让AllYour
声明每个类都将其子类化,请删除@classmethod
装饰器,并在issubclass
调用中切换参数.您在元类上定义的特殊方法不需要特殊修饰.
If you want AllYour
to claim that every class subclasses it, remove the @classmethod
decorator, and switch the arguments in the issubclass
call. Special methods you define on a metaclass don't need special decoration.
这篇关于如何使用__subclasscheck__魔术方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!