Python类和__init__方法

Pan*_*yay 5 python

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

1)BaseClass

2)InheritClass

当我们将InheritClass实例分配给变量时,当InheritClass不包含__init__方法而BaseClass是什么时,会发生什么?

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

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

Fog*_*ird 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
Run Code Online (Sandbox Code Playgroud)

孩子继承了父母的方法.它可以覆盖它们,但它不必.

  • 不,如果子类中不存在,`child.func`将在父类中调用`func`. (2认同)
  • 关键是在创建`Child`时,会隐式调用`Child`的`__init__`方法,只要没有明确定义,它就会被继承. (2认同)
  • 如果你想在`Child .__ init__`方法中调用`Parent .__ init __`,你需要传递子实例`self`,如下所示:`class Child(Parent):def __init __(self):Parent .__ init __(self )#other child stuff` (2认同)