问题
I am having a hard time figuring out the purpose some code that I've come across.
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).
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__
.
回答1:
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
Note, the above call can also be written using super:
class B(A):
def __init__(self, x, y):
super().__init__(x)
self.y = y
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.
回答2:
Python allows you to call the constructor (__init__
) directly. By calling Foo.__init__(obj, 'bar')
, you're doing an initialization/reinitialization of obj
See this code:
class Foo:
def __init__(self, s):
self.s = s
f = Foo('abc')
print(f.s) # prints 'abc'
Foo.__init__(f, 'def')
print(f.s) # prints 'def'
回答3:
Yes - when inheriting class invokes __init__()
of the parent class. AFAIK, this is the only valid case of calling __init__()
explicitly.
来源:https://stackoverflow.com/questions/16126734/what-is-the-purpose-of-calling-init-directly