【发布时间】:2016-02-19 17:38:10
【问题描述】:
我如何编写一个 mixin,如果使用这个特定 mixin 的类没有正确创建,它会引发一个异常。
如果我在 mixin 的 __init__ 或 __new__ 方法中进行这些检查和平衡,当这个错误的类尝试创建实例时会引发异常。这已经晚了,理想情况下,当编译器检测到错误的类时需要抛出异常。 (假设,如何检测一个类是否可以接受是一件小事)
说明问题
class ASampleMixin:
"""
A sample docstring
"""
def a_method(self):
raise NotImplementedError
def class_rule(self):
if something is wrong:
return False
return True
# more methods
class AClass(ASampleMixin, BaseClass):
"""
This class should satisfy a condition specified in class_rule method of the mixin
"""
# some methods
我现在正在执行 mixin 的 init 方法中的检查。如果规则返回 False,则会引发异常。现在这需要在解释器读取 AClass 时完成,而不是在我尝试创建 AClass 实例时完成。
即使在 Python 3.5 等动态类型语言中也有可能吗?
【问题讨论】:
-
谢谢。更正了它。没有关注它,它就流出来了。
标签: python oop python-3.x metaprogramming