Python和对象/类attrs - 发生了什么?

Phi*_*ham 1 python class-attributes

有人能解释为什么Python会做以下事情吗?

>>> class Foo(object):
...   bar = []
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar.append(1)
>>> b.bar
[1]
>>> a.bar = 1
>>> a.bar
1
>>> b.bar
[1]
>>> a.bar = []
>>> a.bar
[]
>>> b.bar
[1]
>>> del a.bar
>>> a.bar
[1]
Run Code Online (Sandbox Code Playgroud)

这让人很困惑!

dan*_*ben 7

这是因为你编写它的方式bar是类变量而不是实例变量.

要定义实例变量,请在构造函数中绑定它:

class Foo(object):
  def __init__(self):
    self.bar = []
Run Code Online (Sandbox Code Playgroud)

请注意,它现在属于Foo(self)而不是Foo类的单个实例,您将看到分配给它时所期望的结果.