class Parent:
def hello(self):
print ("正在调用父类的方法")
class Child(Parent):
pass
子类会继承父类的方法
p = Parent()
p.hello()
正在调用父类的方法
c = Child()
c.hello()
正在调用父类的方法
子类同名函数会调用子类的方法
class Child(Parent):
def hello(self):
print ("正在调用子类的方法")
c = Child()
c.hello()
正在调用子类的方法
当子类重写了_init_ 方法就会覆盖父类的 __init__方法
import random as r
class Fish :
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
class Shark(Fish):
def __init__(self):
self.hungry = True
s = Shark()
s.x
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-de3f64b0c536> in <module>()
1 s = Shark()
----> 2 s.x
AttributeError: 'Shark' object has no attribute 'x'
解决方法 1.重写调用父类的方法
class Fish :
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
class Shark(Fish):
def __init__(self):
Fish.__init__(self)
self.hungry = True
p = Shark()
p.x
10
解决方法 2.使用super方法
class Fish :
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
class Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True
z = Shark()
z.x
9