0

Based on the classes below, I tried to make a dog that would allow instantiating all fields, and I tried:

class Animal(object):
    def __init__(self, legs=4, animal_type='beast'):
        self.legs           = legs
        self.animal_type    = animal_type


class Dog(Animal):
    def __init__(self, name=None, owner=None):
        self.name   = name
        self.owner  = owner

dog = Dog(legs=4, animal_type='dog', name='Fido', owner='Bob')

print dog.owner
print dog.name

which gave TypeError: __init__() got an unexpected keyword argument 'legs'

Based on Initializing subclass variable in Python I tried

class Animal(object):
    def __init__(self, legs=4, animal_type='beast'):
        self.legs           = legs
        self.animal_type    = animal_type


class Dog(Animal):
    def __init__(self, legs=None, animal_type=None, name=None, owner=None):
        if legs:
            self.legs = legs
        if animal_type:
            self.animal_type = animal_type
        self.name   = name
        self.owner  = owner

dog = Dog(name='Fido', owner='Bob')

print dog.name

But here, I got a dog, but legs and animal_type didn't default, in fact, they didn't get set at all (pic below).

enter image description here

This example works to make a dog with 4 legs, but I don't have the ability to default and I have to give the legs and type or it won't create:

class Animal(object):
    def __init__(self, legs=4, animal_type='beast'):
        self.legs           = legs
        self.animal_type    = animal_type


class Dog(Animal):
    def __init__(self, legs, animal_type, name=None, owner=None):
        if legs:
            self.legs = legs
        if animal_type:
            self.animal_type = animal_type
        self.name   = name
        self.owner  = owner

dog = Dog(4, 'dog', name='Fido', owner='Bob')

print dog.name

How can I subclass to be able to optionally overwrite parent attributes that default if they aren't given? So how can I take these classes Animal and Dog, and if I don't say the legs or type get a dog with legs=4, and animal_type=beast? Thank you

1 Answer 1

2
class Animal(object):
    def __init__(self, legs=4, animal_type='beast'):
        self.legs        = legs
        self.animal_type = animal_type


class Dog(Animal):
    def __init__(self, name=None, owner=None, **kwargs):
        super(Dog, self).__init__(**kwargs)
        self.name  = name
        self.owner = owner

dog = Dog(legs=4, animal_type='dog', name='Fido', owner='Bob')

Capture the extra arguments in **kwargs and call the parent's constructor with them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.