错误定义 class 时引发异常
Raise exception while defining a class improperly
我如何编写一个 mixin,如果未正确创建使用此特定 mixin 的 class,它会引发异常。
如果我在 mixin 的 __init__ 或 __new__ 方法中进行这些检查和平衡,当这个错误的 class 尝试创建实例时会引发异常。这已经晚了,理想情况下,当编译器检测到错误 class 时需要抛出异常。 (假设,如何检测 class 是否可以接受是一件小事)
说明问题
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方法中进行检查。如果规则 returns False,则会引发异常。现在这需要在解释器读取 AClass 时完成,而不是在我尝试创建 AClass 的实例时完成。
甚至在 Python 3.5 这样的动态类型语言中也可能吗?
这听起来好像您想创建一个自定义元class,它在创建 class 对象时执行检查。见 documentation for metaclasses.
作为参考的元类示例:
class CustomType(type):
def __call__(cls, *args, **kwargs):
if not CustomType.some_rule(kwargs.pop('some_attr', None)):
raise Exception('Abort! Abort!')
return super(CustomType, cls).__call__(*args, **kwargs)
@staticmethod
def some_rule(var):
if type(var) is not str:
return False
return True
class A(object):
__metaclass__ = CustomType
class B(A):
pass
b = B(some_attr='f') # all is well
b = B() # raises
我如何编写一个 mixin,如果未正确创建使用此特定 mixin 的 class,它会引发异常。
如果我在 mixin 的 __init__ 或 __new__ 方法中进行这些检查和平衡,当这个错误的 class 尝试创建实例时会引发异常。这已经晚了,理想情况下,当编译器检测到错误 class 时需要抛出异常。 (假设,如何检测 class 是否可以接受是一件小事)
说明问题
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方法中进行检查。如果规则 returns False,则会引发异常。现在这需要在解释器读取 AClass 时完成,而不是在我尝试创建 AClass 的实例时完成。
甚至在 Python 3.5 这样的动态类型语言中也可能吗?
这听起来好像您想创建一个自定义元class,它在创建 class 对象时执行检查。见 documentation for metaclasses.
作为参考的元类示例:
class CustomType(type):
def __call__(cls, *args, **kwargs):
if not CustomType.some_rule(kwargs.pop('some_attr', None)):
raise Exception('Abort! Abort!')
return super(CustomType, cls).__call__(*args, **kwargs)
@staticmethod
def some_rule(var):
if type(var) is not str:
return False
return True
class A(object):
__metaclass__ = CustomType
class B(A):
pass
b = B(some_attr='f') # all is well
b = B() # raises