python的构造函数

原文链接

1、FooBar的构造函数

class FooBar:

def __init__(self):

self.somevar = 42

 

>>>f = FooBar()

>>>f.somevar

2、

 

 3、解决办法

将传递类Bird的初始函数写入SongBird的初始化中

class SongBird(Bird):

     def __init__(self):

          Bird.__init__(self)

          self.sound = 'Squawk'

     def sing(self):

          print self.song()

或者使用super函数(只在新式类中有用)

class SongBird(Bird):

     def __init__(self):

          super(SongBird,self).__init__()

          self.sound = 'Squawk'

     def sing(self):

          print self.song()

原理:它会查找所有的超类,以及超类的超类,直到找到所需的特性为止。

posted @ 2020-04-24 19:19  蛮好不太坏  阅读(466)  评论(0编辑  收藏  举报