python的类的属性,可以不用声明,在赋值时直接生效

数据属性相当于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 is the instance of 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

你可能感兴趣的:(python的类的属性,可以不用声明,在赋值时直接生效)