首页 > 解决方案 > 在评估类时,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实例化时,我才能以某种方式让上面的断言在代码执行时进行评估?

这很重要,这样如果有人错误地实现了一个类,应用程序就不会运行。

(我不确定我对标题的措辞是否正确)

标签: python

解决方案


实际上,即使“何时Implementation被实例化”它也不起作用 - 它会Mother通过Child类(Implementation继承Child--->Child继承Mother)找到与类的关系,
从而由于继承链而将其视为从类派生(被isinstance(self, Mother)认为Implementation是(方法分辨率顺序)) 改用钩子:Mothermro
__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类及其子类 - 请改用issubclasscall :

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)

钩子将应用于类声明阶段(在潜在实例化之前)


推荐阅读