|
3鱼币
>>> class C:
... x = []
... def add_x(self, x):
... self.x.append(x)
...
>>> c = C()
>>> d = C()
>>> c.add_x(250)
>>> d.add_x(520)
>>> c.x
请问这里为什么会打印[250,520]呢,不应该只打印[250]吗,用到的是列表的哪条属性呢?
本帖最后由 lxping 于 2022-12-26 13:18 编辑
你定义的x属性为类属性,类名.属性名和类的实例化对象.属性名都可以访问和更改类属性x,
所以当使用d.add_x(520)后,类属性x就已经变成了[250,520],你使用类名C.x同样可以得到这个值[250,520]
要区分类属性和对象属性
类属性
- class C:
- x = []
- def add_x(self, x):
- self.x.append(x)
-
- c = C()
- d = C()
- c.add_x(520)
- d.add_x(250)
- c.x
- [520, 250]
- C.x
- [520, 250]
- d.x
- [520, 250]
- c.__dict__ #没有属性x
- {}
- d.__dict__ #没有属性x
- {}
- C.__dict__ #有属性x
- mappingproxy({'__module__': '__main__', 'x': [520, 250], 'add_x': <function C.add_x at 0x0000020C161CDCF0>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None})
复制代码
对象属性
- class A:
- def __init__(self):
- self.x = []
- def add_x(self, x):
- self.x.append(x)
-
- a = A()
- b = A()
- a.add_x(520)
- b.add_x(250)
- a.x
- [520]
- b.x
- [250]
- a.__dict__ #有属性x
- {'x': [520]}
- b.__dict__ #有属性x
- {'x': [250]}
- A.__dict__ #没有属性x
- mappingproxy({'__module__': '__main__', '__init__': <function A.__init__ at 0x0000020C161CDEA0>, 'add_x': <function A.add_x at 0x0000020C161CDFC0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None})
复制代码
|
最佳答案
查看完整内容
你定义的x属性为类属性,类名.属性名和类的实例化对象.属性名都可以访问和更改类属性x,
所以当使用d.add_x(520)后,类属性x就已经变成了[250,520],你使用类名C.x同样可以得到这个值[250,520]
要区分类属性和对象属性
类属性
对象属性
|