数据类继承变量不起作用

问题描述 投票:0回答:1

我有一个数据类子类,它只是继承变量。我知道关键字变量需要放在最后,但即使如此,子类中变量的顺序似乎也发生了变化。我不明白错误消息告诉我什么

@dataclass
class ZooAnimals():
  

    food_daily_kg: int
    price_food: float 
    area_required: float
    
    name: str = field(default='Zebra', kw_only=True)
   
    
c = ZooAnimals(565, 40, 10, name='Monkey')

Out: ZooAnimals(food_daily_kg=565, price_food=40, area_required=10, name='Monkey')

现在是子类

@dataclass
class Cats(ZooAnimals):
    def __init__(self, food_daily_kg, price_food, area_required, name, meowing):
        meowing: str 
        super().__init__()


z = Cats(465, 30, 10, 'Little Bit', name='Leopard')

Out: TypeError: Cats.__init__() got multiple values for argument 'name'
python inheritance python-dataclasses
1个回答
0
投票

当您只是添加属性时,不需要将

__init__()
dataclass
一起使用:

from dataclasses import dataclass, field
@dataclass
class ZooAnimals():
  
    food_daily_kg: int
    price_food: float 
    area_required: float
    
    name: str = field(default='Zebra', kw_only=True)

@dataclass
class Cats(ZooAnimals):
    meowing: str 


z = Cats(465, 30, 10, 'Little Bit', name='Leopard')

输出:

Cats(food_daily_kg=465, price_food=30, area_required=10, name='Leopard', meowing='Little Bit')
© www.soinside.com 2019 - 2024. All rights reserved.