class object's attribute is also the instance's attribute?

Hans Mulder hansmu at xs4all.nl
Thu Aug 30 11:20:42 EDT 2012


On 30/08/12 16:48:24, Marco Nawijn wrote:
> On Thursday, August 30, 2012 4:30:59 PM UTC+2, Dave Angel wrote:
>> On 08/30/2012 10:11 AM, Marco Nawijn wrote:
>>> On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote:
>>>> <snip>

>>> Learned my lesson today. Don't assume you know something. Test it first ;).

A very important lesson.

Next week's lesson will be: if you test it first, then
paste it into a message for this forum, then tweak just
one unimportant detail, you'll need to test it again.

>>> I have done quite some programming in Python, but did not know that
class
>>> attributes are still local to the instances.

>> They're not.  They're just visible to the instances, except where the
>> instance has an instance attribute of the same name.  Don't be confused
>> by dir(), which shows both instance and class attributes.
>>
>> Please show me an example where you think you observe each instance
>> getting a copy of the class attribute.  There's probably some other
>> explanation.
> 
> I don't have an example. It was just what I thought would happen.
> Consider the following. In a class declaration like this:
> 
> class A(object):
>     attr_1 = 10
> 
>     def __init__(self):
>        self.attr_2 = 20
> 
> If I instantiated it twice:
> 
> obj_1 = A()
> obj_2 = A()
> 
> For both obj_1 and obj_2 attr_1 equals 10. What I thought would happen after the following statement:
> 
> obj_1.attr_1 = 12
> 
> is that obj_2.attr_1 also equals 12. This is what surprised me a little, that's all. 

The trick is to look at obj_1.__dict__ to see what is defined locally:

>>> obj_1 = A()
>>> obj_1.__dict__
{'attr_2': 20}

>>> obj_1.attr_1 = 12
>>> obj_1.__dict__
{'attr_2': 20, 'attr_1': 12}


Hope this helps,

-- HansM



More information about the Python-list mailing list