python - 在评估类时,python 中是否有一种神奇的方法?
问题描述
我有一个 mixin 类,它应该仅在与其他类一起使用时用作接口,例如:
class Mother():
pass
class Child(Mother):
pass
class Mixin():
def __init__(self):
assert isinstance(self, Mother), 'Mixin can only be used with Mother implementations'
super().__init__()
class Implementation(Mixin, Child):
pass
Implementation()
上面的方法有效,但只有在Implementation
实例化时,我才能以某种方式让上面的断言在代码执行时进行评估?
这很重要,这样如果有人错误地实现了一个类,应用程序就不会运行。
(我不确定我对标题的措辞是否正确)
解决方案
实际上,即使“何时Implementation
被实例化”它也不起作用 - 它会Mother
通过Child
类(Implementation
继承Child
--->Child
继承Mother
)找到与类的关系,
从而由于继承链而将其视为从类派生(被isinstance(self, Mother)
认为Implementation
是(方法分辨率顺序))
改用钩子:Mother
mro
__init_subclass__
class Mother():
pass
class Child(Mother):
pass
class Mixin():
def __init_subclass__(cls, **kwargs):
assert isinstance(cls, Mother), 'Mixin can only be used with Mother'
super().__init_subclass__(**kwargs)
class Implementation(Mixin, Child):
pass
Implementation()
抛出:
Traceback (most recent call last):
File ..., in __init_subclass__
assert isinstance(cls, Mother), 'Mixin can only be used with Mother'
AssertionError: Mixin can only be used with Mother
但是,如果您需要允许Mixin
应用于Mother
类及其子类 - 请改用issubclass
call :
class Mixin():
def __init_subclass__(cls, **kwargs):
assert issubclass(cls, Mother), 'Mixin can only be used with Mother and its subclasses'
super().__init_subclass__(**kwargs)
钩子将应用于类声明阶段(在潜在实例化之前)
推荐阅读
- servlets - Servlet 过滤器未初始化,url 映射在 web 片段中不起作用?
- javascript - 检查动态路由快递js
- docker - Docker:无法从控制台登录
- sql - 集团公司及其交易
- sockets - 如何减少通过多播发送的数据包的传输大小?
- html - react-select inputProps 未应用于 AsyncSelect
- javascript - 有没有办法独立处理为多个可观察对象发出的值,然后在所有可观察对象都完成时做一些事情?
- git - 在合并之前将远程 HEAD 重置为特定的提交
- laravel - 使用 vuejs 和 laravel 将嵌套数据存储在文件中
- bash - 将 Xterm 的输出重定向到日志文件