python多继承小游戏_Python多继承,__ init__

bd96500e110b49cbb3cd949968f18be7.png

Regarding multiple parent inheritance, when I call the super.__init__, why doesn't parent2's __init__ function get called? Thanks.

class parent(object):

var1=1

var2=2

def __init__(self,x=1,y=2):

self.var1=x

self.var2=y

class parent2(object):

var4=11

var5=12

def __init__(self,x=3,y=4):

self.var4=x

self.var5=y

def parprint(self):

print self.var4

print self.var5

class child(parent, parent2):

var3=5

def __init__(self,x,y):

super(child, self).__init__(x,y)

childobject = child(9,10)

print childobject.var1

print childobject.var2

print childobject.var3

childobject.parprint()

Output is

9

10

5

11

12

解决方案

If you want to use super in child to call parent.__init__ and parent2._init__, then both parent __init__s must also call super:

class parent(Base):

def __init__(self,x=1,y=2):

super(parent,self).__init__(x,y)

class parent2(Base):

def __init__(self,x=3,y=4):

super(parent2,self).__init__(x,y)

See "Python super method and calling alternatives" for more details on the sequence of calls to __init__ caused by using super.

class Base(object):

def __init__(self,*args):

pass

class parent(Base):

var1=1

var2=2

def __init__(self,x=1,y=2):

super(parent,self).__init__(x,y)

self.var1=x

self.var2=y

class parent2(Base):

var4=11

var5=12

def __init__(self,x=3,y=4):

super(parent2,self).__init__(x,y)

self.var4=x

self.var5=y

def parprint(self):

print self.var4

print self.var5

class child(parent, parent2):

var3=5

def __init__(self,x,y):

super(child, self).__init__(x,y)

childobject = child(9,10)

print childobject.var1

print childobject.var2

print childobject.var3

childobject.parprint()

You might be wondering, "Why use Base?". If parent and parent2 had inherited directly from object, then

super(parent2,self).__init__(x,y) would call object.__init__(x,y). That raises a TypeError since object.__init__() takes no parameters.

To workaround this issue, you can make a class Base which accepts arguments to __init__ but does not pass them on to object.__init__. With parent and parent2 inheriting from Base, you avoid the TypeError.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值