Python中的继承点是什么? [英] What’s the point of inheritance in Python?

查看:78
本文介绍了Python中的继承点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下情况

  #include< iostream> 

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

class Dog:public Animal {
void speak(){std :: cout<< WOFF! <<的std :: ENDL; }
};

class Cat:public Animal {
void speak(){std :: cout<< 喵! <<的std :: ENDL; }
};

void makeSpeak(Animal& a){
a.speak();
}

int main(){
Dog d;
Cat c;
makeSpeak(d);
makeSpeak(c);
}

如您所见,makeSpeak是一个接受通用Animal对象的例程。在这种情况下,Animal非常类似于Java接口,因为它只包含一个纯虚方法。 makeSpeak不知道它传递的Animal的性质。它只是向它发送信号speak并留下后期绑定来处理要调用的方法:Cat :: speak()或Dog :: speak()。这意味着,就makeSpeak而言,实际传递哪个子类的知识是无关紧要的。



但是Python呢?让我们看看Python中相同案例的代码。请注意,我尝试尽可能与C ++案例尽可能相似:

  class Animal(object):
def speak(self):
raise NotImplementedError()

class Dog(Animal):
def speak(self):
printwoff!

class Cat(动物):
def speak(self):
printmeow

def makeSpeak(a):
a.speak()

d = Dog()
c = Cat()
makeSpeak(d)
makeSpeak(c)

现在,在此示例中,您会看到相同的策略。您使用继承来利用Dogs和Cats都是动物的分层概念。
但是在Python中,不需要这种层次结构。这同样适用

  class Dog:
def speak(self):
printwoff!

class Cat:
def speak(self):
printmeow

def makeSpeak(a):
a.speak ()

d = Dog()
c = Cat()
makeSpeak(d)
makeSpeak(c)

在Python中,您可以将发言信号发送到您想要的任何对象。如果对象能够处理它,它将被执行,否则它将引发异常。假设您向两个代码添加了一个类飞机,并将一个Airplane对象提交给makeSpeak。在C ++的情况下,它不会编译,因为Airplane不是Animal的派生类。在Python的情况下,它会在运行时引发异常,这甚至可能是预期的行为。



另一方面,假设您使用方法添加MouthOfTruth类说话()。在C ++的情况下,要么必须重构层次结构,要么必须定义不同的makeSpeak方法来接受MouthOfTruth对象,或者在java中,您可以将行为提取到CanSpeakIface并为每个对象实现接口。有很多解决方案...



我想指出的是,我还没有找到一个在Python中使用继承的原因(除了框架之外)和异常的树木,但我想存在替代策略)。您不需要实现基于派生的层次结构来执行多态。如果您想使用继承来重用实现,您可以通过包含和委派来完成相同的操作,并且可以在运行时更改它,并且您可以清楚地定义所包含的接口,而不会产生意外的副作用。



所以,最后,问题在于:Python中的继承点是什么?



编辑:感谢非常有趣的答案。实际上,您可以将它用于代码重用,但在重用实现时我总是很小心。一般来说,我倾向于做非常浅的继承树或根本没有树,如果一个功能很常见,我将它重构为一个通用模块例程,然后从每个对象调用它。我确实看到了有一个单一变化点的优势(例如,而不是添加到Dog,Cat,Moose等,我只是添加到Animal,这是继承的基本优势),但你可以实现相同的代表链(例如,JavaScript)。我并没有声称它更好,只是另一种方式。



我还发现关于这方面的类似帖子。

你指的是运行时鸭子类型作为重写继承,但我相信继承作为一种设计和实现方法有其自身的优点,是一个不可或缺的部分面向对象设计。在我看来,你是否可以实现某些目标的问题并不是很相关,因为实际上你可以在没有类,函数等的情况下编写Python代码,但问题是代码的设计,健壮和可读性如何。



在我看来,我可以举两个例子说明继承是正确的方法,我相信还有更多。



首先,如果您明智地编码,您的makeSpeak函数可能想要验证其输入确实是Animal,而不仅仅是它可以说,在这种情况下最优雅的方法是使用继承。同样,您可以通过其他方式实现,但这是面向对象设计的继承之美 - 您的代码将真正检查输入是否是动物。



<第二,显然更直接的是封装 - 面向对象设计的另一个不可或缺的部分。当祖先具有数据成员和/或非抽象方法时,这变得相关。采取以下愚蠢的例子,其中祖先有一个函数(speak_twice)调用then-abstract函数:

  class Animal (对象):
def speak(self):
raise NotImplementedError()

def speak_twice(self):
self.speak()
self .speak()

class Dog(动物):
def speak(self):
printwoff!

class Cat(动物):
def speak(self):
printmeow

假设speak_twice是一个重要的功能,你不想在Dog和Cat中编码它,我'我相信你可以推断这个例子。当然,你可以实现一个Python独立函数,它将接受一些duck-typed对象,检查它是否有一个speak函数并调用它两次,但这都是非优雅的并且错过了第一个点(验证它是一个Animal)。更糟糕的是,为了加强Encapsulation示例,如果后代类中的成员函数想要使用speak_twice怎么办?



如果祖先类有一个数据成员,例如number_of_legs,祖先类中的非抽象方法使用它,如<$ c,它会变得更加清晰$ c>print_number_of_legs,但是在后代类的构造函数中启动(例如,Dog会用4初始化它,而Snake会用0初始化它)。



同样,我确信还有更多的例子,但基本上每个(足够大的)基于实体面向对象设计的软件都需要继承。


Suppose you have the following situation

#include <iostream>

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

class Dog : public Animal {
    void speak() { std::cout << "woff!" <<std::endl; }
};

class Cat : public Animal {
    void speak() { std::cout << "meow!" <<std::endl; }
};

void makeSpeak(Animal &a) {
    a.speak();
}

int main() {
    Dog d;
    Cat c;
    makeSpeak(d);
    makeSpeak(c);
}

As you can see, makeSpeak is a routine that accepts a generic Animal object. In this case, Animal is quite similar to a Java interface, as it contains only a pure virtual method. makeSpeak does not know the nature of the Animal it gets passed. It just sends it the signal "speak" and leaves the late binding to take care of which method to call: either Cat::speak() or Dog::speak(). This means that, as far as makeSpeak is concerned, the knowledge of which subclass is actually passed is irrelevant.

But what about Python? Let’s see the code for the same case in Python. Please note that I try to be as similar as possible to the C++ case for a moment:

class Animal(object):
    def speak(self):
        raise NotImplementedError()

class Dog(Animal):
    def speak(self):
        print "woff!"

class Cat(Animal):
    def speak(self):
        print "meow"

def makeSpeak(a):
    a.speak()

d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)

Now, in this example you see the same strategy. You use inheritance to leverage the hierarchical concept of both Dogs and Cats being Animals. But in Python, there’s no need for this hierarchy. This works equally well

class Dog:
    def speak(self):
        print "woff!"

class Cat:
    def speak(self):
        print "meow"

def makeSpeak(a):
    a.speak()

d=Dog()
c=Cat()
makeSpeak(d)
makeSpeak(c)

In Python you can send the signal "speak" to any object you want. If the object is able to deal with it, it will be executed, otherwise it will raise an exception. Suppose you add a class Airplane to both codes, and submit an Airplane object to makeSpeak. In the C++ case, it won’t compile, as Airplane is not a derived class of Animal. In the Python case, it will raise an exception at runtime, which could even be an expected behavior.

On the other side, suppose you add a MouthOfTruth class with a method speak(). In the C++ case, either you will have to refactor your hierarchy, or you will have to define a different makeSpeak method to accept MouthOfTruth objects, or in java you could extract the behavior into a CanSpeakIface and implement the interface for each. There are many solutions...

What I’d like to point out is that I haven’t found a single reason yet to use inheritance in Python (apart of frameworks and trees of exceptions, but I guess that alternative strategies exist). you don’t need to implement a base-derived hierarchy to perform polymorphically. If you want to use inheritance to reuse implementation, you can accomplish the same through containment and delegation, with the added benefit that you can alter it at runtime, and you clearly define the interface of the contained, without risking unintended side effects.

So, in the end, the question stands: what's the point of inheritance in Python?

Edit: thanks for the very interesting answers. Indeed you can use it for code reuse, but I am always careful when reusing implementation. In general, I tend to do very shallow inheritance trees or no tree at all, and if a functionality is common I refactor it out as a common module routine and then call it from each object. I do see the advantage of having one single point of change (eg. instead of adding to Dog, Cat, Moose and so on, I just add to Animal, which is the basic advantage of inheritance), but you can achieve the same with a delegation chain (eg. a la JavaScript). I'm not claiming it's better though, just another way.

I also found a similar post on this regard.

解决方案

You are referring to the run-time duck-typing as "overriding" inheritance, however I believe inheritance has its own merits as a design and implementation approach, being an integral part of object oriented design. In my humble opinion, the question of whether you can achieve something otherwise is not very relevant, because actually you could code Python without classes, functions and more, but the question is how well-designed, robust and readable your code will be.

I can give two examples for where inheritance is the right approach in my opinion, I'm sure there are more.

First, if you code wisely, your makeSpeak function may want to validate that its input is indeed an Animal, and not only that "it can speak", in which case the most elegant method would be to use inheritance. Again, you can do it in other ways, but that's the beauty of object oriented design with inheritance - your code will "really" check whether the input is an "animal".

Second, and clearly more straightforward, is Encapsulation - another integral part of object oriented design. This becomes relevant when the ancestor has data members and/or non-abstract methods. Take the following silly example, in which the ancestor has a function (speak_twice) that invokes a then-abstract function:

class Animal(object):
    def speak(self):
        raise NotImplementedError()

    def speak_twice(self):
        self.speak()
        self.speak()

class Dog(Animal):
    def speak(self):
        print "woff!"

class Cat(Animal):
    def speak(self):
        print "meow"

Assuming "speak_twice" is an important feature, you don't want to code it in both Dog and Cat, and I'm sure you can extrapolate this example. Sure, you could implement a Python stand-alone function that will accept some duck-typed object, check whether it has a speak function and invoke it twice, but that's both non-elegant and misses point number 1 (validate it's an Animal). Even worse, and to strengthen the Encapsulation example, what if a member function in the descendant class wanted to use "speak_twice"?

It gets even clearer if the ancestor class has a data member, for example "number_of_legs" that is used by non-abstract methods in the ancestor like "print_number_of_legs", but is initiated in the descendant class' constructor (e.g. Dog would initialize it with 4 whereas Snake would initialize it with 0).

Again, I'm sure there are endless more examples, but basically every (large enough) software that is based on solid object oriented design will require inheritance.

这篇关于Python中的继承点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆