有没有办法在Python的子类中多次包含相同的Mixin?

2024-10-04 11:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

通常,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中可能吗?谢谢。你知道吗


Tags: childbasestringascolumnpassdescriptionmixin
1条回答
网友
1楼 · 发布于 2024-10-04 11:23:34

我建议使用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。你知道吗

相关问题 更多 >