通常,Python mixin只包含一次,例如:
class MyMixin:
pass
class Child(Base, MyMixin):
pass
然而,在某些情况下,如果我们可以使用同一个Mixin两次,这将是很方便的。 例如,我在SQLAlchemy中有一个Mixin,它定义了以下列:
class MyNoteMixin:
note = Column(String)
by_who = Column(String)
现在我有一个子类继承了上面的Mixin,但是需要两个不同的列,它们都是note性质的。我可以这样做吗:
class Child(Base, MyNoteMixin as "Description", MyNoteMixin as "Quote"):
pass
因此,解析的表将包含一个名为Description的列,该列除名称外完全是MyNoteMixin副本,并且还有另一个名为Quote的列具有相同的性质。你知道吗
炼金术可以吗?或者一般来说,Mixin的这种用法在Python中可能吗?谢谢。你知道吗
我建议使用python decorator。你知道吗
下面是一个如何使用plan python类获取此值的示例:
输出:
您必须将其调整为sqlalchemy,比如将
setattr
连接到您的MyNoteMixin
。你知道吗相关问题 更多 >
编程相关推荐