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

Hans Mulder hansmu at xs4all.nl
Thu Aug 30 09:25:22 EDT 2012


On 30/08/12 14:34:51, Marco Nawijn wrote:
> Note that if you change 'd' it will change for all instances!

That depends on how you change it.
>>>> bobj = A()
>>>> bobj.d
> 'my attribute'
>>>>> A.d = 'oops...attribute changed'

Here you change the attribute on the class.
That will affect all instances:
>>>> aobj.d
> 'oops...attribute changed'
>>>>> bobj.d
> 'oops...attribute changed'

You can also set the attribute on an instance:
>>> bobj.d = 'For bobj only'
>>> bobj.d
'For bobj only'
>>>> aobj.d
> 'oops...attribute changed'

So, if you specifically change it on one instance, thenit won't
change on other instances of the same class.
> If you want attributes to be local to the instance, you have
> to define them in the __init__ section of the class like this:

That's a good idea, but it's not required. You can set them
later, as shown above.
> class A(object):
>> def __init__(self):
> d = 'my attribute'

That will just set the global variable d.
You want to set the instance attribute:
 self.d = 'my attribute'
>>>> aobj = A()
>>>> bobj = A()
>>>>> aobj.d
> 'my attribute'

Note that aobj.d will not find the global variable d,
if neither the instance, nor the class nor any of the
base classes have that attribute.
I don't know where this 'my attribute' comes from, but
it's not the instance attribute you tried to set in the
__init__ method. Maybe your class A still has a class
attribute with that value from an earlier experiment.
Hope this helps,
-- HansM


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /