[Tutor] common (sub)attributes

Alan Gauld alan.gauld at btinternet.com
Wed Feb 24 23:47:05 CET 2010


"spir" <denis.spir at free.fr> wrote

> Classes are often used to hold common or default attribute.

True

> Then, some of these attrs may get custom values for individual
> objects of a given type. Simply by overriding the attr on this object

Yes, but then the arttribute becomes an instance attribute which masks
the class one (unless accessed via the class).

> But this will not only if the attr is a top-level one; not if it is 
> itself part
> of a composite object.

Sorry, you lost me there!

> In the latter case, the (sub)attribute is still shared, so the change
> affects everybody. So, we must redefine the whole top-level attr
> instead. Trivial, but not obvious for me ;-)

Nope, Didn't understand that either. Not sure what you mean by
a sub-attribute or top-level attribute?.

> === sample code ===
> #!/usr/bin/env python
> # coding: utf-8
>
> # case x is top-level attr
> class C(object):
> x = 0
> y = 0
> a = 'u'
> def __str__ (self) :
> return "C(%s,%s,%s)" %(self.x,self.y,self.a)

Using an instance to access class attributes is IMHO a bad idea.
Better to always access class attributes via the class, it makes it
obvious what you are working with.

> c1 = C() ; c2 = C()
> c1.x = 1 # change x for c1 only
> c1.a = 'v' # change a for c1 only

Really creating new instance attributes called x and a


> print c1,c2 # ==> C(1,0,v) C(0,0,u)

> # case x is element of composite attr
> class P:
> x = 0
> y = 0
> class C(object):
> p = P()
> a = 'u'
> def __str__ (self) :
> return "C(%s,%s,%s)" %(self.p.x,self.p.y,self.a)
> c1 = C() ; c2 = C()
> c1.p.x = 1 # change x for c1, but x is actually shared

Yes but try P.x, it will have the original value of 0
You are again creating a new instance attribute in the instance
of P which is shared by the class C.

> c1.a = 'v' # change a for c1 only

Create a new instance variable a

This is consistent with how Python deals with ocal variables in a function:

x = 0

print x
def f()
    print x
    x = 5
    print x

print x

prints

0
0
5
0

The 5 is local to the function and only exists for the duration of the code 
execution.
In the case of an instance the "local" or instyance barianle lasts for the 
life of
the object. The class variable last for the life of the class. (and in 
Python you
can del() a class... to end its life - but it will exist until the last 
instance is
destroyed because each instance has a reference to it.)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list