PHP和Python支持多继承吗,Python类--继承与多继承

目的是可以代码重用

class  DerivedClassName (BassClassName)class Parent:

def hello():

print ‘正在调用父类方法’

class Child (Parent): #  继承了父类的方法

pass>> p = Parent()

>> p.hello()

正在调用父类方法

>> c = Child()

>> c.hello()

正在调用父类方法

当子类中定义和父类同名的方法和属性时,则会覆盖父类的方法和属性。class Parent:

def hello():

print ‘正在调用父类方法’

class Child (Parent):#  继承了父类的方法

def hello():

print ‘正在调用子类方法’>> p = Parent()

>> p.hello()

正在调用父类方法

>> c = Child()

>> c.hello()

正在调用子类方法

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

***************************************************************************#########**************************************************************************

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%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 ‘我的位置是在:’, self.x ,self.y

class Goldfish(Fish):

pass

class Charp(Fish):

pass

class Salmon(Fish):

pass

class Shark(Fish):

def __init__(self):   ################## 这一步很容易造成错误,因为覆盖了父类的__init__函数

self.hungry = True

def eat(self):

if self.hungry:

print '真好吃!'

self.hungry = False

else:

print '现在还不饿'>> fish = Fish()

>> fish.move()  # 向上移动一步

(0,0)

>> fish.move() # 继续向上移动一步

(-1,0)>> fish2 = Goldfish()

>> fish2.move()  # 向上移动一步

(1,5)

>> fish2.move() # 继续向上移动一步

(0,5)>> fish3 = Shark()

>> fish3.eat()

print '真好吃!'

>> fish3.move()  # 向上移动一步

此时报错,由于 Shark类在定义的时候 定义的 __init__(self) 覆盖了父类Fish的__init__(self)函数

解决覆盖父类__init__函数的方法有两种:1 调用未绑定的父类方法;    加入父类名.__init__(self)

class Shark(Fish):

def __init__(self):

Fish.__init__(self)    ################## 加入所有父类的__init__函数

self.hungry = True

def eat(self):

if self.hungry:

print '真好吃!'

self.hungry = False

else:

print '现在还不饿'接下来就可以了。

>> fish3 = Shark()

>> fish3.move()

(3,2)

>> fish3.move()

(2,2)2 使用super函数;    加入super( ). __init__( )

class Shark(Fish):

def __init__(self):

super( ). __init__( )    ################## 直接用super,不需要父类的名字

self.hungry = True

def eat(self):

if self.hungry:

print '真好吃!'

self.hungry = False

else:

print '现在还不饿'

多重继承: 慎用! 会产生不可预测的bug

class  DerivedClassName (Bass1,Bass2, Bass3, ...)class Bass1:

def fool1(self):

print ' w x w'

class Bass2:

def fool2(self):

print ' w y w'

class Child(Bass1,Bass2):

pass>> c = Child()

>> c.fool1()

w x w

>> c.fool2()

w y w

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值