通常,只包含一次Python mixin,例如:
class MyMixin:
pass
class Child(Base, MyMixin):
pass
但是,在某些情况下,如果我们可以两次使用相同的Mixin,将很方便。例如,我在SQLAlchemy中有一个Mixin,定义了一些列,如下所示:
class MyNoteMixin:
note = Column(String)
by_who = Column(String)
现在,我有一个继承自上述Mixin的子类,但需要两个不同的列,两者均具有注释性质。我可以做类似的事情吗?
class Child(Base, MyNoteMixin as "Description", MyNoteMixin as "Quote"):
pass
这样,解析后的表将包含一个名为Description的列,除了名称外,该列完全是MyNoteMixin副本,并且AND还具有另一个具有相同性质的名为Quote的列。
SQLAlchemy是否可能?或一般来说,在Python中甚至可以使用Mixin吗?谢谢。
我建议使用python decorator。
这是一个使用plan python类的示例:
def custom_fields(**kwargs):
def wrap(original_class):
"""
Apply here your logic, could be anything!
"""
for key, val in kwargs.items():
setattr(original_class, key, val)
return original_class
return wrap
@custom_fields(quote='String here, can be SQLAlchemy column object')
class Child:
pass
print(Child.quote)
输出:
>>> String here, can be SQLAlchemy column object
你将不得不去适应它SQLAlchemy的,就像连接setattr
到你的MyNoteMixin
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句