1,当类属性为不可变的值时,不可以通过实例对象去修改类属性

class Foo(object):
    x = 1.5

foo = Foo()
print(foo.x)         #输出:1.5
print(id(foo.x))     #输出:2400205363696

foo.x = 1.7
print(foo.x)         #输出:1.7
print(id(foo.x))     #输出:2400203142352   和上面的id不一样,表明已经新创建了一个实例属性
print(Foo.x)         #输出:1.5

 

2,当类属性为可变的值时,可以过实例对象去修改类属性

class Foo(object):
    x = [1,2,3]

foo = Foo()
print(foo.x)       #输出:[1, 2, 3]
print(id(foo.x))   #输出:1999225501888

foo.x[2] = 4
print(foo.x)      #输出:[1, 2, 4]
print(id(foo.x))  #输出:1999225501888
print(Foo.x)      #输出:[1, 2, 4]

foo.x.append(5)
print(foo.x)      #输出:[1, 2, 4, 5]
print(id(foo.x))  #输出:1999225501888
print(Foo.x)      #输出:[1, 2, 4, 5]

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-04
  • 2022-12-23
  • 2021-11-25
  • 2021-09-21
  • 2022-12-23
  • 2021-07-20
猜你喜欢
  • 2022-01-06
  • 2022-12-23
  • 2021-05-07
  • 2022-12-23
  • 2021-08-28
  • 2021-05-24
  • 2022-12-23
相关资源
相似解决方案