python中是否有一个神奇的方法用于计算类?
我有一个mixin类,它应该仅在与其他类一起使用时用作接口,例如:python中是否有一个神奇的方法用于计算类?,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 Implem
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()
上面的方法是有效的,但是只有当实现
被实例化时,我才能在代码执行时对上面的断言进行评估
这一点很重要,这样,如果有人错误地实现了一个类,应用程序就不会运行
(我不确定标题的措辞是否正确)事实上,即使“当
实现
正在实例化时”,它也不会起作用-它会通过子类(实现
继承子类
->子类
继承母类
)找到与母类的关系,
因此,isinstance(self,Mother)
将实现
视为继承链(被视为mro
(方法解析顺序))
使用钩子代替:
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
调用:
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)
钩子将应用于类声明阶段(潜在实例化之前)您也可以使用元类,它功能强大,可以帮助您理解python类
class-Mother():
通过
班级儿童(母亲):
通过
类元(类型):
定义新(元cls、名称、基础、dct):
如果名称!=“Mixin”和所有([不发布b类(b,母类)中的b类]:
引发异常(“Mixin只能与母亲一起使用”)
cls=super()
返回cls
类Mixin(元类=Meta):
通过
类实现(Mixin、Child):
通过
即使“在实例化实现时”,它也不会工作-它会通过Child
类(至少在Python>=3.4上)找到与母亲的关系。这是为了更具体地编辑代码,所以希望class
语句引发异常?这将需要更改为类型。\uuuu new\uuuuu
;无论Mixin做什么,都应该直接折叠到母类中。@chepner是的,我有一个暗示,我做得不对,最后我希望能够有不同的继承类组合,所以我想到了这个“模块化”方法,而不是为每个可能的组合使用不同的类,但这是预期的结果result@Mojimi你是什么意思?你的意思是“Mixin只能与Mother及其子类一起使用”
?(参见附加的和)是的,它需要是母亲的例子,这是代码所说的,但这不是问题,汉克斯,没有意识到这一点