Python类和

2024-04-25 21:37:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

1)基类

2)继承类

当我们将一个InheritClass实例赋给一个变量时,当InheritClass不包含__init__方法而BaseClass包含时,到底会发生什么?在

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

实际上文件信息.py这个例子让我头痛得厉害,我只是不明白事情是怎么回事。跟随


Tags: 文件实例方法文档py信息init基类
2条回答

@FogleBird已经回答了你的问题,但我想补充一些东西,不能评论他的帖子:

您可能还想看看^{} 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__甚至是同名的方法!在

是,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

子级继承其父级的方法。它可以覆盖它们,但不必。在

相关问题 更多 >

    热门问题