如何使用__subclasscheck__魔术方法? [英] How to use the __subclasscheck__ magic method?

查看:125
本文介绍了如何使用__subclasscheck__魔术方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何才能使一个关于谁被欺骗的谎言的阶级呢?

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__魔术方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆