python构造方法报错_python 学习笔记-构造方法

Python中的构造函数是形如 def__init__(self),例如class Bird:

def __init__(self):

self.hungry=True

def eat(self):

if self.hungry:

print‘Ahhhh‘

self.hungry=False

else:

print ‘no,thx‘

实例化类Bird对象b:

b=Bird()

b.eat()

b.eat()

Ahhhh

no,thx

假设现在Bird有一个子类Songbird(),继承了Bird()的方法和属性,class Songbird(Bird):

def __init__(self):

self.sound=‘ohlaohaloha‘

def sing(self):

print self.sound

sb=Songbird()

sb.eat()

sb.eat()

调用后我们看到系统报错,因为Songbird的构造方法并没有任何关于hungry的代码。

AttributeError: Songbird instance has no attribute ‘hungry‘

尝试在子类Songbird的构造方法中增加超类中的方法eat(),也得到相同错误,因为eat()方法含有hungry变量。

那么如何在子类中调用超类的构造方法来初始化,使子类实例具有超类实例呢?提供两种方法:

1. 调用未绑定的超类构造方法:

class Songbird(Bird):

def __init__(self):

Bird.__init__(self)

self.sound=‘ohlaohaloha‘

def sing(self):

print self.sound

在子类中增加一行  Bird.__init__(self) , 那么子类的实例化对象就可以使用超类的构造方法的所有实现。sb=Songbird()

sb.eat()

sb.eat()

Ahhhh

no,thx

2. 使用super方法来调用超类中的方法,这里指的是__init__构造方法。

class Songbird(Bird):

def __init__(self):

super(Songbird,self).__init__()

self.sound=‘ohlaohaloha‘

def sing(self):

print self.sound

这样使用前必须加上from _pyio import __metaclass__

__metaclass__=type

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值