繁体   English   中英

Python类和__init__方法

[英]Python classes and __init__ method

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

1) BaseClass

2) InheritClass

InheritClass不包含__init__方法和BaseClass时,我们将一个InheritClass实例分配给一个变量时到底发生了什么?

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

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

是的,将自动调用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

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

@FogleBird已经回答了你的问题,但我想添加一些东西,不能对他的帖子发表评论:

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

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__方法,甚至是同名的方法!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM