Class 数据类中的属性和元类
Class Attribute and metaclass in dataclasses
我有一些 Python class 具有 class 属性和元 class:
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
改进代码:如何处理class属性c_type
和c_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 should be annotated with 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_type
或 c_brand
属性。
我有一些 Python class 具有 class 属性和元 class:
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
改进代码:如何处理class属性c_type
和c_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 should be annotated with 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_type
或 c_brand
属性。