《零基础入门学习python》038笔记:类的继承
本帖最后由 汪蛋 于 2017-9-7 21:37 编辑{:10_327:} {:10_327:} {:10_327:}
知识点一:超厉害的super
class Ball:
def __init__(self):
self.color = 'yellow'
def hello(self):
print("Hello, this ball is %s" % self.color)
class BallA(Ball):
def __init__(self):
print("This ball is A") 运行上面一段代码,会发现,BallA类虽然继承了Ball类,但是由于子类的__init__函数覆盖了基类的__init__,导致在BallA中并没有给self.color赋值,也就是BallA无法正常继承hello函数。可以有两种办法解决这个问题,Ball类不变,将BallA做如下改进:# 方法一:
class BallA(Ball):
def __init__(self):
Ball.__init__(self)
print("This ball is A")# 方法二:
class BallA(Ball):
def __init__(self):
super().__init__()
print("This ball is A") super的好处在于,当基类为多个时,仍然只需要这一条语句就可以解决了,而方法一则需要针对每一个基类写一条。是不是很厉害丫~~~{:10_264:}{:10_264:}{:10_264:}
知识点二:多重继承
class BallA:
def hello1(self):
print("This ball is A")
class BallB:
def hello2(self):
print("This ball is A")
class C(BallA, BallB):
pass
c = C()
c.hello1()
c.hello2() 如果BallA和BallB中的hello函数名设为同一个,那么只会输出BallA中的hello。 class BallA:
def __init__(self):
self.color = "yellow"
def hello(self):
print("This ball is A")
class BallB:
def __init__(self):
self.weight = 10
def hello(self):
print("This ball is B")
class C(BallA, BallB):
def __init__(self):
super().__init__()
BallB.__init__(self)
c = C()
c.color,c.weight
如果不写BallB.__init__(self)
c.weight 就会报错哎,,,光写super().__init__()不行额
页:
[1]