简体   繁体   中英

Python object's attribute

I have a python question about object's attribute. Code:

>>> 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'}

I'm a PHP devlopper and in PHP rint b.dict will be {} . Why python share this attribute between a and b ? What is the way to define class attribute who will be new on new instantiation?

You created a class attribute , not an instance attribute. The dictionary is mutable, you can alter it from instances or on the class directly, but class attributes are by definition shared among all instances.

Create a new empty dictionary in the __init__ method instead:

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

    def stuff(self, name):
        self.dict[name] = 'toto'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM