Python类和__init__方法

时间:2011-07-26 14:32:52

标签: python

我正在通过深入python学习python。几乎没有问题,也无法理解,即使是通过文档。

1) BaseClass

2) InheritClass

InheritClass 不包含__init__方法且 BaseClass <时,我们将 InheritClass 实例分配给变量时会发生什么? / em>呢?

  • 是否自动调用 BaseClass __init__方法
  • 另外,请告诉我在引擎盖下发生的其他事情。

实际上fileInfo.py的例子让我很头疼,我只是无法理解事情是如何运作的。以下

2 个答案:

答案 0 :(得分:6)

是的,BaseClass.__init__将自动调用。父类中定义的任何其他方法也是如此,但子类不是。观察:

>>> class Parent(object):
...   def __init__(self):
...     print 'Parent.__init__'
...   def func(self, x):
...     print x
...
>>> class Child(Parent):
...   pass
...
>>> x = Child()
Parent.__init__
>>> x.func(1)
1

孩子继承了父母的方法。它可以覆盖它们,但它没有。

答案 1 :(得分:4)

@FogleBird已经回答了你的问题,但我想补充一些内容而无法评论他的帖子:

您可能还想查看super function。这是一种从孩子内部调用父方法的方法。想要扩展方法时有用,例如:

class ParentClass(object):
    def __init__(self, x):
        self.x = x

class ChildClass(ParentClass):
    def __init__(self, x, y):
        self.y = y
        super(ChildClass, self).__init__(x)

这当然可以包含更复杂的方法, __init__方法,甚至是同名的方法!