python - 数据类中的类属性和元类

标签 python python-dataclasses

我有一些带有类属性和元类的 Python 类:

from abc import ABCMeta

class OldProduct(metaclass=ABCMeta):
    c_type: str
    c_brand: str

    def __init__(self, name:str):
        self.name = name

class OldLegoBox(OldProduct):
    c_type = "Toy"
    c_brand = "Lego"

    def __init__(self, name:str, price:float):
        self.name = name
        self.price = price

oldbox1 = OldLegoBox("Princess", 12.3)
print(oldbox1.c_brand)
oldbox2 = OldLegoBox("Knight", 42.3)
print(oldbox2.c_brand)

我想使用dataclasses来改进代码:如何处理类属性c_typec_brand

我正在考虑以下似乎可以满足我的需求:

from abc import ABCMeta
from dataclasses import dataclass, field


@dataclass
class Product(metaclass=ABCMeta):
    c_type: str
    c_brand: str
    name: str


@dataclass
class LegoBox(Product):
    name: str
    price: float
    c_type: str = field(default="Toy", init=False)
    c_brand: str = field(default="Lego", init=False)


box1 = LegoBox("Princess", 12.3)
print(box1)
box1.price = 1000
box1.name = "toto"
box1.c_brand = "some brand"
print(box1)
box2 = LegoBox("Knight", 42.3)
print(box2)

有更合适的方法吗?

最佳答案

Dataclass class variables应注释为 typing.ClassVar

@dataclass
class Product(metaclass=ABCMeta):
    c_type: ClassVar[str]
    c_brand: ClassVar[str]
    name: str

@dataclass
class LegoBox(Product):
    c_type: ClassVar[str] = "Toy"
    c_brand: ClassVar[str] = "Lego"
    price: float

据我所知,使用抽象类实际上并没有给你带来任何好处,因为没有抽象方法。您仍然可以创建 Product 实例,但它们不会具有 c_typec_brand 属性。

关于python - 数据类中的类属性和元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57966177/

相关文章:

python - 如何更改 view.py 中 django-tables2 表的列标题?

Python 正则表达式在与 re.findall 一起使用时返回匹配的一部分

python - 如何忽略传递给数据类的额外参数?

python - 数据类参数是否有别名或名称参数?

python - 避免在 Python 的数据类字段中显式使用 `default` 关键字

python - 如果我需要行数并且需要附加到文件,我可以避免处理文件两次吗?

python - 在python中从unicode(对于外语)段落中提取主题标签

python - 如何创建一个处理具有不同名称的嵌套字典的数据类?

python - 与MongoDB结合使用Dataclass中的 '_id'应该如何处理?

python - 使用 Ctypes 在 Python 中加载已编译的 Matlab 共享库