How to use the __subclasscheck__ magic method?

╄→гoц情女王★ 提交于 2019-12-08 06:05:18

问题


How can we make a class who lies about who he has subclassed?

After reading the doc I've attempted this:

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

But it didn't work:

>>> issubclass(AllYour, int)
False

Why not?


回答1:


If you want AllYour to claim to be a subclass of every class, that isn't possible. __subclasscheck__ works in the other direction.

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.



来源:https://stackoverflow.com/questions/34623610/how-to-use-the-subclasscheck-magic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!