Reputation: 371
I want to have a single 'animal' class which has some properties. Then inside the animal class, I give it properties depending on the type of animal. The result is a long list of if else statements inside my class.
Ideally, I would want something like the following:
class animal(type):
pass
class cat(self, age, height):
initalize properties
class dog(self, age, height):
initialize properties
And then I want to create the animal class like
new_animal = animal(age, height)
How can I achieve this? Thanks!
Upvotes: 0
Views: 260
Reputation: 43
Usually to perform inheritance, you start by defining the Parent class, which should be generic enough to justify inheritance for other child classes.
In your case, about animals and their properties, I would rather define an Animal class as a Parent class, and then your different animals would inherit this Animal class. Here's a minimalist example :
class Animal():
def __init__(self, age, height):
self.age = age
self.height = height
def print_height(self):
print(self.height)
class Cat(Animal):
def __init__(self, age, height, meowness):
super().__init__(age, height)
self.meowness = meowness
my_cat = Cat(age=2, height=35, meowness=0.5)
my_cat.print_height()
Which outputs
35
Then you can tune the Animal class to contain whatever information all your different animals would be characterized by (can include methods as well).
Note that characteristics specific to an animal should not be in the parent class, such as the meowness I added to the Cat class
Upvotes: 2
Reputation: 33
Hopefully this answers your question, I would do the following:
class Animal:
def __init__(self, age, height):
self.age = age
self.height = height
def printAge(self):
print(self.age)
def printHeight(self):
print(self.height)
class Cat(Animal):
def __init__(self, age, height, catBreed="British Shorthair"):
super().__init__(age, height) # Inherit methods and properties from parent
self.catBreed = catBreed
class Dog(Animal):
def __init__(self, age, height, barkLoudness=3):
super().__init__(age, height) # Inherit methods and properties from parent
self.barkLoudness = barkLoudness
Upvotes: 1