原文链接

1、FooBar的构造函数

class FooBar:

def __init__(self):

self.somevar = 42

 

>>>f = FooBar()

>>>f.somevar

2、

python的构造函数

 

 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()

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-18
  • 2021-08-03
  • 2022-12-23
  • 2021-09-30
  • 2021-09-10
猜你喜欢
  • 2021-07-31
  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案