Python对象的属性

时间:2013-11-07 12:32:39

标签: python

我有一个关于object属性的python问题。代码:

>>> class A(object):
...   dict = {}
...   def stuff(self, name):
...     self.dict[name] = 'toto'
... 
>>> a = A()
>>> print a.dict
{}
>>> a.stuff('un')
>>> print a.dict
{'un': 'toto'}
>>> b = A()
>>> print b.dict
{'un': 'toto'}

我是PHP devlopper,在PHP rint b.dict中将是{}。为什么python在ab之间共享此属性?在新实例化中定义将成为 new 的类属性的方法是什么?

1 个答案:

答案 0 :(得分:3)

您创建了类属性,而不是实例属性。字典是可变的,您可以直接从实例或类中更改它,但是根据定义,类属性在所有实例之间共享。

__init__方法中创建一个新的空字典:

class A(object):
    def __init__(self):
        self.dict = {}

    def stuff(self, name):
        self.dict[name] = 'toto'
相关问题