What’s the point of inheritance in Python?

前端 未结 11 2106
一向
一向 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

    Classes in Python are basically just ways of grouping a bunch of functions and data.. They are different to classes in C++ and such..

    I've mostly seen inheritance used for overriding methods of the super-class. For example, perhaps a more Python'ish use of inheritance would be..

    from world.animals import Dog
    
    class Cat(Dog):
        def speak(self):
            print "meow"
    

    Of course cats aren't a type of dog, but I have this (third party) Dog class which works perfectly, except the speak method which I want to override - this saves re-implementing the entire class, just so it meows. Again, while Cat isn't a type of Dog, but a cat does inherit a lot of attributes..

    A much better (practical) example of overriding a method or attribute is how you change the user-agent for urllib. You basically subclass urllib.FancyURLopener and change the version attribute (from the documentation):

    import urllib
    
    class AppURLopener(urllib.FancyURLopener):
        version = "App/1.7"
    
    urllib._urlopener = AppURLopener()
    

    Another manner exceptions are used is for Exceptions, when inheritance is used in a more "proper" way:

    class AnimalError(Exception):
        pass
    
    class AnimalBrokenLegError(AnimalError):
        pass
    
    class AnimalSickError(AnimalError):
        pass
    

    ..you can then catch AnimalError to catch all exceptions which inherit from it, or a specific one like AnimalBrokenLegError

提交回复
热议问题