语法
class 类名(被继承的类):
.....
看代码,其实很好理解
>>> class Parent:
... def hello(self):
... print("正在调用父类方法")
...
>>> class Child(hello):
... pass
...
>>> p = Parent()
>>> p.hello()
正在调用父类方法
>>> c = Child()
>>> c.hello()
正在调用父类方法
>>>
嗯哼哼?其实就相当于就用,继承者相当于子类,pass是什么,空的意思方便大家理解,官方点就是占位符
看一个吃鱼的小游戏(源代码)
import random as r#调用
class Fish:#一个类
def __init__(self):#还记得上一章的魔法方法吗__init__可以实实例化对像来代入参数
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
self.x -=1
print("我的位置是",self.x,self.y)
def goldfish(Fish):
pass
def carp(Fish):
pass
def Salmon(Fish):
pass
class Shark(Fish):#定义鲨鱼,一个傻鲨鱼
def __init__(self):#这里会讲到调用未绑定的父类方法
self.hungry = True
def eat(self):
if self.hungry:
print("我是个大吃货")
self.hungry = False
else:
print("饱了,不吃了")
运行后,发现鲨鱼报错了
>>> fish = Fish()
>>> fish.move()
我的位置是 2 7
>>> shark = Shark()
>>> shark.move()
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
shark.move()
File "C:/Users/Administrator/Desktop/魔法方法.py", line 10, in move
self.x -=1
AttributeError: 'Shark' object has no attribute 'x'
>>>
原因是,调用__init__时重新定义,无法实现移动 改下代码
完美
这里的self是子类的self而不是父类的self替代
代码
class Shark(Fish):
def __init__(self):
Fish.__init__(self)
self.hungry = True
def eat(self):
if self.hungry:
print("我是个大吃货")
self.hungry = False
else:
print("饱了,不吃了")
有没有更好的方法呢?
有的super函数
class Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print("我是个大吃货")
self.hungry = False
else:
print("饱了,不吃了")
运行如下
>>> shark = Shark()
>>> shark.move()
我的位置是 4 9
直接原话开始解释
super的超级之处在于你不许要明确的给出任何基类的名字,他会自动的帮你找出所有基类以及对应的方法。意味着如果需要改变类的继承关系,只需要改变class语句里的父类即可。
多重继承
语法
class 类名(父类1,父类2,父类3......)
.......
看代码,秒懂
class Base1:
def fool(self):
print("我是fool,我在Basel中")
class Base2:
def foo2(self):
print("我是foo2,我在Basel中")
class Cat(Base1,Base2):
pass
运行后
>>> cat = Cat()
>>> cat.fool()
我是fool,我在Basel中
>>> cat.foo2()
我是foo2,我在Basel中
>>>
当然不建议使用的,会造成bug的