python 子类继承父类和实例化子类后参数调用
一个例子
class Parent:
def __init__(self, a=1, b=2, c=3):
self.a = a
self.b = b
self.c = c
# 子类中覆盖父类参数有两种方法:1,调用父类的初始化方法和2,覆盖父类的参数
class Child(Parent):
def __init__(self, b=20, c=30, d=40):
# 调用父类的初始化方法
super().__init__(c=c)
# 覆盖父类的b参数
self.b = b
# 添加新的参数d
self.d = d
# 实例化Parent
p = Parent()
print(p.a, p.b, p.c) # 输出: 1 2 3
# 从子类Child()实例化一个c,不传参数,使用子类Child()的默认参数
c = Child()
print(c.a, c.b, c.c, c.d) # 输出: 1 20 30 40
# 从子类Child()实例化一个m,传参数,改变子类Child()的默认参数
m = Child(b=5, c=6, d=7)
print(m.a, m.b, m.c, m.d) # 输出: 1 20 30 40
m = Child(a=4, b=5, c=6, d=7)
# 报错 TypeError: __init__() got an unexpected keyword argument 'a'
# 这体现了类继承的安全性.子类Child()继承自父类Parent的时候,虽然父类Parent定义了参数a,但是子类Child()没有定义参数a,因而子类Child()
# 继承了父类Parent的属性,可以从子类Child()中读取属性a,但是不能更改属性a,除非直接在子类Child()中定义参数a.