被继承的类称为基类、父类或超类;继承者称为子类,一个子类可以继承它的父类的任何属性和方法。举个例子:
# 类名大写,方法名小写,约定俗称
class Parent:
def hello(self):
print("using parent's class...")
class Child(Parent):
pass
p = Parent()
p.hello()
using parent's class...
c = Child()
c.hello()
using parent's class...
- 子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法
继承
例子:
import random as r
# 父类
Class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y - r.randint(0, 10)
def move(self):
self.x -= 1
print("my seat: ", self.x, self.y)
# 子类
Class Shark(Fish):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print("i want eat...")
self.hungry = False
else:
print("I am full, don't eat...")
shark = Shark()
shark.move()
Trackback (most recent call last):
AttributeError: 'Shark' object has no attribute 'x'
# 原因:在shark类中,重写了__init__()方法,但是新的__init__()方法里没有初始化父类的属性(这里是x,y),因此调用move方法就会出错。结局方法:使用super函数
class Shark(Fish):
def __init__(self):
super().__init__()
...