VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • python魔术方法详解(3)

 

异常很清楚地说明了错误:SongBird没有hungry特性。原因是这样的:在SongBird中,构造方法被重写,但新的构造方法没有任何关于初始化hungry特性的代码。为了达到预期的效果,SongBird的构造方法必须调用其超类Bird的构造方法来确保进行基本的初始化。

两种方法实现:

一 、调用未绑定的超类构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Bird:
    def __init__(self):
        self.hungry= True
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry= False
        else:
            print 'No, thanks!'
             
class SongBird(Bird):
         def __init__(self):
                 Bird.__init__(self)
                 self.sound= 'Squawk!'
         def sing(self):
                 print self.sound
>>> s= SongBird()
>>> s.sing()
Squawk!
>>> s.eat()
Aaaah...
>>> s.eat()
No, thanks!

 

在SongBird类中添加了一行代码Bird.__init__(self) 。 在调用一个实例的方法时,该方法的self参数会被自动绑定到实例上(这称为绑定方法)。但如果直接调用类的方法,那么就没有实例会被绑定。这样就可以自由地提供需要的self参数(这样的方法称为未绑定方法)。

通过将当前的实例作为self参数提供给未绑定方法,SongBird就能够使用其超类构造方法的所有实现,也就是说属性hungry能被设置。

二、使用super函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
__metaclass__= type  #表明为新式类
class Bird:
    def __init__(self):
        self.hungry= True
    def eat(self):
        if self.hungry:
            print 'Aaaah...'
            self.hungry= False
        else:
            print 'No, thanks!'
             
class SongBird(Bird):
         def __init__(self):
                 super(SongBird,self).__init__()
                 self.sound= 'Squawk!'
         def sing(self):
                 print self.sound
>>> s.sing()
Squawk!
>>> s.eat()
Aaaah...
>>> s.eat()
No, thanks!

相关教程