可以随时在初始化的python对象中分配属性。
它们不必在初始化时完成,您甚至可以从对象外部分配它们。
>>> class A:
... def __init__(self):
... self.a = 1
... def thing(self):
... self.b = 2
...
>>> c=A()
>>> c.a
1
>>> c.b
Traceback (most recent call last):
module __main__ line 141
traceback.print_exc()
module <module> line 1
c.b
AttributeError: 'A' object has no attribute 'b'
>>> c.thing()
>>> c.b
2
>>> c.c = 3
>>> c.c
3
编辑:根据@roganjosh的评论,您可以将其指定为
none
在初始化过程中。你不仅得不到
AttributeError
>>> class A:
... def __init__(self):
... self.a = 1
... self.b = None
... def thing(self):
... if self.b is None:
... self.b = 2
...
>>> c=A()
>>> c.b
None
>>> c.thing()
>>> c.b
2
>>> c.b = 3
>>> c.thing()
>>> c.b
3