python - 如何使用mixins与pony orm共享属性

标签 python inheritance mixins ponyorm

有没有办法共享pony.orm中实体的属性定义? 我有几个彼此不相关的类,但我希望它们具有相同的属性。目前我将它们从一个类(class)复制粘贴到另一个类(class),但一旦我更改措辞或添加/删除属性,这将是大量的手动工作。

有什么办法可以改变这个

class ClassA(db.Entity):
    primary: str = orm.PrimaryKey(str)

    classa_key1: str = orm.Required(str)
    classa_key2: str = orm.Required(str)
    classa_key3: str = orm.Required(str)
    ...

    some_key1: str = orm.Required(str)
    some_key2: str = orm.Required(str)
    ...

class ClassB(db.Entity):
    primary: str = orm.PrimaryKey(str)

    classb_key1: str = orm.Required(str)
    classb_key2: str = orm.Required(str)
    classb_key3: str = orm.Required(str)
    ...

    some_key1: str = orm.Required(str)
    some_key2: str = orm.Required(str)
    ...

变成这样的东西?

class SomeKeyMixin:
    some_key1: str = orm.Required(str)
    some_key2: str = orm.Required(str)
    ...


class ClassA(db.Entity, SomeKeyMixin):
    primary: str = orm.PrimaryKey(str)

    classa_key1: str = orm.Required(str)
    classa_key2: str = orm.Required(str)
    classa_key3: str = orm.Required(str)
    ...


class ClassB(db.Entity, SomeKeyMixin):
    primary: str = orm.PrimaryKey(str)

    classb_key1: str = orm.Required(str)
    classb_key2: str = orm.Required(str)
    classb_key3: str = orm.Required(str)
    ...

普通继承不起作用,因为这会将所有类放入同一个表中,这是不希望的。

最佳答案

不幸的是,使用 Pony 似乎无法实现你想要的。这就是他们在文档中所说的。它们只提供一种实现继承的方法,即将所有内容放在一张表中。

https://docs.ponyorm.org/entities.html#representing-inheritance-in-the-database

关于python - 如何使用mixins与pony orm共享属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61724223/

相关文章:

Python3.3 : . format() with unicode format_spec

python - 打破 python 多处理管理器列表

python - Airflow 网络服务器获取值错误 :Samesite

ruby-on-rails - "The Ruby way"(mixins 和类重新打开)与依赖注入(inject)

c# - Mixins 和 .net

python - 遍历 pandas 数据框中的所有列以按分隔符拆分

c++ - 调用基类方法的简洁(但仍然富有表现力)C++ 语法

c# - 返回子类实例的方法

ios - SWIFT 如何创建一个 NSCoding 子类并从另一个类调用它?

html - 如何在 SASS 中定义动态混合或函数名称?