Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

Need help understanding class inheritance in python

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!

question from:https://stackoverflow.com/questions/65626643/need-help-understanding-class-inheritance-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...