问题
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