class object's attribute is also the instance's attribute?
Marco Nawijn
nawijn at gmail.com
Thu Aug 30 10:11:06 EDT 2012
On Thursday, August 30, 2012 3:25:52 PM UTC+2, Hans Mulder wrote:
> 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
Learned my lesson today. Don't assume you know something. Test it first ;). I have done quite some programming in Python, but did not know that class attributes are still local to the instances. It is also a little surprising I must say. I always considered them like static variables in C++ (not that I am an expert in C++).
I knew of course that you don't have to define a local attribute in the __init__ method of a class, but I consider it good style and since the OP is a self claimed newbie I left out the other option.
The missing "self" in the code below was a typo
class A(object):
def __init__(self):
d = 'my attribute' # should be self.d
Regards,
Marco
More information about the Python-list
mailing list