What’s the point of inheritance in Python?

前端 未结 11 2113
一向
一向 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 10:59

    In C++/Java/etc, polymorphism is caused by inheritance. Abandon that misbegotten belief, and dynamic languages open up to you.

    Essentially, in Python there is no interface so much as "the understanding that certain methods are callable". Pretty hand-wavy and academic-sounding, no? It means that because you call "speak" you clearly expect that the object should have a "speak" method. Simple, huh? This is very Liskov-ian in that the users of a class define its interface, a good design concept that leads you into healthier TDD.

    So what is left is, as another poster politely managed to avoid saying, a code sharing trick. You could write the same behavior into each "child" class, but that would be redundant. Easier to inherit or mix-in functionality that is invariant across the inheritance hierarchy. Smaller, DRY-er code is better in general.

提交回复
热议问题