【发布时间】:2016-01-10 14:01:40
【问题描述】:
根据Learn Python The Hard Way ex44和super()与__init__一起使用的说明:
class Child(object):
def __init__(self, stuff):
self.stuff = stuff
super(Child, self).__init__()
这与上面的
Child.altered示例几乎相同, 除了我在__init__中设置一些变量之前Parent用它的Parent.__init__.初始化
所以实例化Child 也会导致实例化Parent。但是这个实例化是什么/在哪里?给定:
c = Child()
Parent 对象在哪里/是什么?
【问题讨论】:
-
c是 “Parent对象”。一个Child对象是一个Parent对象,这就是继承的重点。在Parent.__init__中,self将引用c,Child实例,就像它在Child.__init__中所做的那样(或者,更确切地说,将分配给c的实例一次所有__init__s 已经跑了)。 -
我将使用 cmets 表达两个个人意见:第一:LPTHW 可能非常可怕,我建议您至少使用一本辅助书籍或资源(例如 dive into python、the python tutorial 或 Python 3 OOP 2nd Ed by Dusty Phillips(最后一个不是免费的))。第二:不错的用户名。
-
@jonrsharpe so "Parent initialize with its
Parent.__init__" 并不意味着创建了一个单独的对象(c除外)? -
没错。正如我所解释的,您正在对新的
Child对象调用Parent的__init__方法。c = Child()仅创建一个 Child 对象,而不是单独的Parent对象。 -
@Pyderman 还有什么不清楚的地方吗?
标签: python python-2.7 inheritance subclass