为什么在这种情况下插入超类的__init __()? [英] Why inserting __init__() of superclass in this case?
问题描述
我现在正在阅读HeadFirstPython,并且有一个关于类的例子。
> class NamedList(list):
>>>> def __init __(self,a_name):
>>> list .__ init __([])
>>> self.name = a_name
在这种情况下,为什么是 list .__ init__ ([])
used?
也不能理解为什么它包含空 []
。
正常,因为它是 调用您继承的类的初始化器。
但是,作者似乎已将 self
替换为空列表;我将使用以下之一:
super(NamedList,self).__ init __()
super(NamedList, self).__ init __([])
或至少提供一个明确的 self
参数:
list .__ init __(self)
在这种情况下,您正在子类化 list
;它的初始化器接受一个初始的元素列表,但是你自己的初始化器只需要 a_name
,所以超类初始化器传递一个明确的空列表。
list .__ init __()
方法比清除和扩展更多;它等效于 self.clear(); self.extend(argument)
,重置它的大小,并使其可重复使用,如果 __ init __()
被多次调用。
将一个新的列表对象传递给列表
初始化器使调用完全无用,并且是无操作的;这是一个错误,必须由技术审查滑落。
I am now reading HeadFirstPython and there is an example about class.
>>> class NamedList(list):
>>> def __init__(self, a_name):
>>> list.__init__([])
>>> self.name = a_name
In this case why is the statement list.__init__([])
used?
And also cannot understand why it is including the empty []
.
Normally, because it is good practice to call the initializer of the class you are inheriting from.
However, the author seems to have substituted self
for an empty list; I'd have used one of:
super(NamedList, self).__init__()
super(NamedList, self).__init__([])
or at the very least provided an explicit self
argument:
list.__init__(self)
In this case, you are subclassing list
; it's initializer takes a initial list of elements to start with, but your own initializer only takes a_name
, so the superclass initializer is passed an explicit empty list.
The list.__init__()
method does little more than clear and extend; it is the equivalent of self.clear(); self.extend(argument)
, resetting it's size and making it re-usable in case __init__()
is called multiple times.
Passing in a new list object to the list
initializer makes the call entirely useless and a no-op; that's an error that must've slipped by the technical review.
这篇关于为什么在这种情况下插入超类的__init __()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!