1

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?

1 Answer 1

3

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.