前面省略继承含义的解释,直接上代码了,更直观点
(1)继承,调用父类属性方法
class Father():
def __init__(self):
self.a='aaa'
def action(self):
print('调用父类的方法')
class Son(Father):
def __init__(self):
self.a='bbb'
def action(self):
print('子类重写父类的方法')
son=Son() # 子类Son继承父类Father的所有属性和方法
son.action() # 调用action方法,这里是自身的action方法而不是父类的action方法
son.a
首先,继承一个类:Son类 继承Father类
class Father():
def __init__(self):
self.a='aaa'
def action(self):
print('调用父类的方法')
class Son(Father):
pass
son=Son() # 子类Son 继承父类Father的所有属性和方法
son.action() # 调用父类方法
son.a # 调用父类属性
输出结果:
注意:在上面的例子中,子类Son没有属性和action的方法,所以会从父类调用,那我们再来看看,子类Son有自身的属性和方法的结果是怎样的?
上述代码修改为:
class Father():
def __init__(self):
self.a='aaa'
def action(self):
print('调用父类的方法')
class Son(Father):
def __init__(self):
self.a='bbb'
def action(self):
print('子类重写父类的方法')
son=Son() # 子类Son继承父类Father的所有属性和方法
son.action() # 子类Son调用自身的action方法而不是父类的action方法
son.a
输出结果:
这里,子类Son已经重写了父类Father的action的方法,并且子类Son也有初始化,因此,子类会调用自身的action方法和属性。总结:如果子类没有重写父类的方法,当调用该方法的时候,会调用父类的方法,当子类重写了父类的方法,默认是调用自身的方法。
另外,如果子类Son重写了父类Father的方法,如果想调用父类的action方法,可以利用super()
代码:
#如果在重新父类方法后,调用父类的方法
class Father():
def action(self):
print('调用父类的方法')
class Son(Father):
def action(self):
super().action()
son=Son()
son.action()
输出结果:
(2)强制调用父类私有属性方法
如果父类的方法是私有方法,如 def __action(self) 这样的话再去调用就提示没有这个方法,其实编译器是把这个方法的名字改成了 _Father__action(),如果强制调用,可以这样:
代码:
class Father():
def __action(self): # 父类的私有方法
print('调用父类的方法')
class Son(Father):
def action(self):
super()._Father__action()
son=Son()
son.action()
输出结果:
(3)调用父类的__init__方法
如果自己也定义了 __init__ 方法,那么父类的属性是不能直接调用的,比如下面的代码就会报错
class Father():
def __init__(self):
self.a=a
class Son(Father):
def __init__(self):
pass
son=Son()
print(son.a)
结果报错:
修改方法:可以在 子类的 __init__中调用一下父类的 __init__ 方法,这样就可以调用了
class Father():
def __init__(self):
self.a='aaa'
class Son(Father):
def __init__(self):
super().__init__()
#也可以用 Father.__init__(self) 这里面的self一定要加上
son=Son()
print(son.a)
输出结果:
增加一个函数,参数是继承父类初始化过程中的参数,作为例子,看看结果
代码:
class Father():
def __init__(self):
self.a=1
self.b=2
class Son(Father):
def __init__(self):
super().__init__()
#也可以用 Father.__init__(self) 这里面的self一定要加上
def add(self):
return self.a+self.b
son=Son()
print(son.add())
输出结果:
以上是关于Python类的继承,调用父类的属性和方法基础内容,在编程过程中,所遇到的几种继承和调用父类属性所应该注意的问题,上述案例都列举出来,可以自己动手写些案例,加深理解。