python的類的屬性,可以不用宣告,在賦值時直接生效
阿新 • • 發佈:2018-11-09
資料屬性相當於Smalltalk中的例項變數,和C++中的資料成員。資料屬性不需要宣告,像區域性變數一樣,當第一次給它分配值的時候,它就立即建立並存在了。
data attributes correspond to “instance variables” in Smalltalk, and to “data members” in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. For example, if x
MyClass
created above, the following piece of code will print the value 16
, without leaving a trace:
例如,如果上文中的MyClass類的例項x已建立,下面的程式碼將列印16,且不留痕跡。
x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print(x.counter) del x.counter
https://docs.python.org/3.7/tutorial/classes.html#instance-objects