我正在通过深入python学习python。几乎没有问题,也无法理解,即使是通过文档。
1) BaseClass
2) InheritClass
当 InheritClass 不包含__init__
方法且 BaseClass <时,我们将 InheritClass 实例分配给变量时会发生什么? / em>呢?
__init__
方法实际上fileInfo.py的例子让我很头疼,我只是无法理解事情是如何运作的。以下
答案 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__
方法,甚至是同名的方法!