# 20201204_108.super()获得父类的定义 原创

1324-易同学

### super()获得父类定义

super()的作用是调用父类的定义（可以理解为代码），不是父类对象。

【案例】

class A:
def say(self):
print('A:', self)

class B(A):
def say(self):
A.say(self)
print('B:', self)

B().say()


class A:
def say(self):
print('A:', self)

class B(A):
def say(self):
super().say()
print('B:', self)

B().say()


#### super()有什么用？

There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

1. 简单的1对1继承关系中，如果父类的名字较长，懒得打那么多字，可以用super()。哈哈哈，外国朋友们是很会偷懒的；
2. 在复杂的多重继承关系中，包括有兄弟姊妹类的关系中，由于有__mro__机制存在，用super()可以使调用的代码永远都是那个直接的父类，即便继承关系发生变化也是这样。这样就避免了在维护时只要继承关系一变化就绪要去修改调用的父类对象名称的麻烦。

Vieu3.3主题

Q Q 登 录