The __init__
method is not special. The only thing that makes __init__
interesting is the fact that it gets called when you call MyClass()
.
The following are equivalent:
# Set inside __init__
class MyClassA:
def __init__(self):
self.x = 0
obj = MyClassA()
# Set inside other method
class MyClassB:
def my_initialize(self):
self.x = 0
obj = MyClassB()
obj.my_initialize()
# Set from outside any method, no self
class MyClassC:
pass
obj = MyClassC()
obj.x = 0
What makes an instance variable is when you assign it, and that can happen anywhere. Also note that self
is not special either, it's just an ordinary function parameter (and in fact, you can name it something other than self
).
so that the memory is properly reserved for this variable per instance.
You do not need to "reserve memory" in Python. With ordinary object instances, when you assign self.x = 0
or obj.x = 0
, it is kind of like putting a value in a dictionary. In fact,
# This is sometimes equivalent, depending on how obj is defined
obj.__dict__['x'] = 0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…