直接调用__init__的目的是什么? [英] What is the purpose of calling __init__ directly?
问题描述
我很难弄清我遇到的一些代码的用途.
I am having a hard time figuring out the purpose some code that I've come across.
该代码具有一个类Foo
,该类具有一个带有多个参数的__init__
方法.到目前为止,从我对Python的了解中,通过调用Foo('bar')
,它将把此字符串作为参数传递给__init__
(我认为应该等效于构造函数).
The code has a class Foo
, which has an __init__
method that takes multiple arguments. From what I've learned of Python so far, by calling Foo('bar')
, it will pass this string as a parameter to __init__
(which I think is supposed to be the equivalent of a constructor).
但是我遇到的问题是我正在查看的代码正在直接调用Foo.__init__('bar')
.这样做的目的是什么?我几乎觉得我在__init__
后面缺少其他用途.
But the issue I am having is that the code I am looking at is calling Foo.__init__('bar')
directly. What is the purpose of this? I almost feel that I am missing some other purpose behind __init__
.
推荐答案
实例化一个类时,将为您调用__init__()
方法.但是,父类中的__init__()
方法不会自动调用,因此如果要扩展其功能,则需要直接调用它:
The __init__()
method gets called for you when you instantiate a class. However, the __init__()
method in a parent class doesn't get called automatically, so need you to call it directly if you want to extend its functionality:
class A:
def __init__(self, x):
self.x = x
class B(A):
def __init__(self, x, y):
A.__init__(self, x)
self.y = y
请注意,上述调用也可以使用 super 编写em> :
Note, the above call can also be written using super:
class B(A):
def __init__(self, x, y):
super().__init__(x)
self.y = y
__init__()
方法的用途用于初始化类.它通常负责填充实例变量.因此,您希望对类层次结构中的所有类调用__init__()
.
The purpose of the __init__()
method is to initialize the class. It is usually responsible for populating the instance variables. Because of this, you want to have __init__()
get called for all classes in the class hierarchy.
这篇关于直接调用__init__的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!