子类调用父类方法主要分为两种:
1. 指名道姓
class A:
def __init_(self,name,age):
self.name = name
self.age = age
class B(A):
def _init__(self,name,age,sex):
A.__init__(self,name,age)
self.sex=sex
a = A("lili","18")
b = B("hannah","20","girl")
print(a.__dict__)
print(b.__dict__)
2. super()
class A:
def __init_(self,name,age):
self.name = name
self.age = age
class B(A):
def _init__(self,name,age,sex):
A.__init__(self,name,age)
super(B,self).__init__(name,age)#python2 只能使用super(B,self)。python3 super(B,self)等于super(),两者皆可
self.sex=sex
a = A("lili","18")
b = B("hannah","20","girl")
print(a.__dict__)
print(b.__dict__)
2.两者区别
指名道姓不依赖于继承,指名道姓是: 类.函数 ,有几个值传几个
super依赖于继承,严格说可以说是依赖于MRO(Method resolution order)表. super(当前类,self)或者super()可以理解为是父类的对象 对象.方法 不需传self