What’s the point of inheritance in Python?

前端 未结 11 2127
一向
一向 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:07

    I think that it is very difficult to give a meaningful, concrete answer with such abstract examples...

    To simplify, there are two types of inheritance: interface and implementation. If you need to inherit the implementation, then python is not so different than statically typed OO languages like C++.

    Inheritance of interface is where there is a big difference, with fundamental consequences for the design of your software in my experience. Languages like Python does not force you to use inheritance in that case, and avoiding inheritance is a good point in most cases, because it is very hard to fix a wrong design choice there later. That's a well known point raised in any good OOP book.

    There are cases where using inheritance for interfaces is advisable in Python, for example for plug-ins, etc... For those cases, Python 2.5 and below lacks a "built-in" elegant approach, and several big frameworks designed their own solutions (zope, trac, twister). Python 2.6 and above has ABC classes to solve this.

提交回复
热议问题