Search code examples
pythoninheritancepython-dataclasses

Dataclass inheritance variables not working


I have a dataclass subclass that is just inheriting variables. I know the keyword variables need to come last, but even with that, the order of variables in the subclass seems to have changed. I don't understand what the error message is telling me

@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')

Now the subclass

@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'

Solution

  • Please try if the following code snippet works for you

    from dataclasses import dataclass
    from dataclasses import field
    
    @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')
    
    @dataclass
    class Cats(ZooAnimals):
        meowing: str
        def __init__(self, meowing, food_daily_kg, price_food, area_required, name):
            self.meowing = meowing
            super().__init__(food_daily_kg, price_food, area_required, name=name)
    
    z = Cats('Little Bit', 465, 30, 10, name='Leopard')
    
    • ZooAnimals class looks good
    • Cats class had issue with variable declaration and variable assignment for meawing.
    • Cats class had issue with variable ordering for meawing.