What’s the point of inheritance in Python?

前端 未结 11 2122
一向
一向 2020-12-12 10:11

Suppose you have the following situation

#include 

class Animal {
public:
    virtual void speak() = 0;
};

class Dog : public Animal {
             


        
11条回答
  •  清歌不尽
    2020-12-12 11:00

    You can get around inheritance in Python and pretty much any other language. It's all about code reuse and code simplification though.

    Just a semantic trick, but after building your classes and base classes, you don't even have to know what's possible with your object to see if you can do it.

    Say you have d which is a Dog that subclassed Animal.

    command = raw_input("What do you want the dog to do?")
    if command in dir(d): getattr(d,command)()
    

    If whatever the user typed in is available, the code will run the proper method.

    Using this you can create whatever combination of Mammal/Reptile/Bird hybrid monstrosity you want, and now you can make it say 'Bark!' while flying and sticking out its forked tongue and it will handle it properly! Have fun with it!

提交回复
热议问题