多态

继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写。

动态语言的鸭子类型特点决定了继承不像静态语言那样是必须的。

多态_第1张图片
file-like object 鸭子类型
多态_第2张图片
Inheritance

Python的“file-like object“就是一种鸭子类型。对真正的文件对象,它有一个read()方法,返回其内容。但是,许多对象,只要有read()方法,都被视为“file-like object“。许多函数接收的参数就是“file-like object“,你不一定要传入真正的文件对象,完全可以传入任何实现了read()方法的对象。

但是,建议来了:

Most of the uses of inheritance can be simplified or replaced with composition, and multiple inheritance should be avoided at all costs.

What is Inheritance?
Inheritance is used to indicate that one class will get most or all of its features from a parent class. This happens implicitly whenever you write class Foo(Bar), which says "Make a class Foo that inherits from Bar." When you do this, the language makes any action that you do on instances of Foo also work as if they were done to an instance of Bar. Doing this lets you put common functionality in the Bar class, then specialize that functionality in the Fooclass as needed.When you are doing this kind of specialization, there are three ways that the parent and child classes can interact:

  • Actions on the child imply an action on the parent.
  • Actions on the child override the action on the parent.
  • Actions on the child alter the action on the parent.

Inheritance Versus Composition

class Parent(object):
    def implicit(self):
        print("PARENT implicit()")
class Child(Parent):
    pass
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
多态_第3张图片
Implicit Inheritance 隐式继承

使用pass表示子类继承父类全部行为,没有什么增加或者变更,似乎
这样的子类也没有。子类和父类总是会有不同的行为,同一功能的实际运行方式结果并不相同。

class Parent(object):
    def override(self):
        print("PARENT override()")
class Child(Parent):
    def override(self):
        print("CHILD override()")
dad = Parent()
son = Child()
dad.override()
son.override()
多态_第4张图片
Override Explicitly 显式重载

子类继承的功能重新定义后,拥有了自己特有的该功能的新版本。

子类的某功能重载后,再次调用父类的功能也是可以的,需要使用super全局函数来返回父类,在调用父类的统一功能。

class Parent(object):
    def altered(self):
        print( "PARENT altered()")
class Child(Parent):
    def altered(self):
        print( "CHILD, BEFORE PARENT altered()")
        super(Child, self).altered()
        print( "CHILD, AFTER PARENT altered()")
dad = Parent()
son = Child()
dad.altered()
son.altered()
多态_第5张图片
super(Child,self)返回父类

你可能感兴趣的:(多态)