通常情况下,继承父类后,有时候要扩展父类的类方法的功能来满足子类的需求。
父亲会写字,但不会写代码
class Father:
# 我会写字
def write(self):
print("我会写字")
class Son(Father):
# 重写Son类的write()方法
# 我会代码
def write(self):
print("我会写代码")
son = Son()
son.write()
super()函数
class Father:
def __init__(self, name):
self.name = name
def write(self):
print("我会写字")
class Son:
def __init__(self, code):
self.code = code
def coding(self):
print("我会写代码:", self.code)
class Person(Father, Son):
pass
person = Person('父亲')
# 调用父类中的 write() 方法
person.write()
person.coding()
运行结果:
我会写字
Traceback(most recent call last):
File"
AttributeError:'Person’object has no attribute ‘coding’
调用Person.coding时报错,Person继承Father与Son,它们都有__init__(构造方法),所以Son的构造方法被“遮蔽”self.code = code没有运行,调用coding()方法时并没有找到self.code。
调用父类构造方法的方式有2种:
- super()函数:该函数只能调用第一个直接父类的构造方法。
- 用类调用方法,只不过需要额外备注类名(可以调用所以直接父类的构造方法):
super() 函数有一种更简单的语法格式,推荐大家使用这种格式:
super()__init__(self, ...)
修改上面程序,调用其他构造方法(__init):
class Father:
def __init__(self, name):
self.name = name
def write(self):
print("我会写字")
class Son:
def __init__(self, code):
self.code = code
def coding(self):
print("我会写代码:", self.code)
class Person(Father, Son):
def __init(self, name, code):
# 调用 People 类的构造方法
super().__init__(name)
# super(Person, self).__init__(name) # 执行效果和上一行相同
# Father.__init__(self, name) # 使用未绑定方法调用 Father 类构造方法
# 调用其他父类的构造方法,需手动给 self 传值
Son.__init__(self, code)
person = Person('父亲', '写代码')
# 调用父类中的 write() 方法
person.write()
person.coding()
输出结果:
我会写字
我会写代码:写代码
Son.__init__(self, code)调用Son(__init__)构造方法,而非Father(__init__)构造方法。



