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).
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
