简体   繁体   English

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

[英]Is there a way to include the same Mixin more than once in a subclass in Python?

Normally a Python mixin would only be included once, like:通常一个 Python mixin 只会被包含一次,比如:

class MyMixin:
    pass
class Child(Base, MyMixin):
    pass

However, in some situation it would be handy if we can use the same Mixin twice.但是,在某些情况下,如果我们可以两次使用相同的 Mixin 会很方便。 For example, I have a Mixin in SQLAlchemy defining some Columns as follow:例如,我在 SQLAlchemy 中有一个 Mixin 定义了一些列,如下所示:

class MyNoteMixin:
    note = Column(String)
    by_who = Column(String)

Now I have a subclass that inherits from the above Mixin, but needs two different columns both are of a note nature.现在我有一个继承自上述 Mixin 的子类,但需要两个不同的列,它们都具有注释性质。 Can I do something like:我可以做这样的事情:

class Child(Base, MyNoteMixin as "Description", MyNoteMixin as "Quote"):
        pass

So that the resolved table would contain a column named Description that is exactly a MyNoteMixin copy except for the name, AND also has another column named Quote with the same nature.这样解析后的表将包含一个名为 Description 的列,该列除了名称外完全是 MyNoteMixin 副本,并且还有另一个具有相同性质的名为 Quote 的列。

Is this possible with SQLAlchemy?这可以用 SQLAlchemy 实现吗? Or generally speaking, is such usage of Mixin even possible in Python?或者一般来说,在 Python 中甚至可以使用 Mixin 吗? Thanks.谢谢。

I would recommend using python decorator .我建议使用python 装饰器

Here is an example how to get this using plan python class:以下是如何使用计划 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)

Output:输出:

>>> String here, can be SQLAlchemy column object

You will have to adapt it for sqlalchemy, like connect the setattr to your MyNoteMixin .您将不得不针对MyNoteMixin进行调整,例如将setattr连接到您的MyNoteMixin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM