Hello,

Just a really basic note:
Classes are often used to hold common or default attribute. Then, some of these 
attrs may get custom values for individual objects of a given type. Simply by 
overriding the attr on this object (see code below). But this will not only if 
the attr is a top-level one; not if it is itself part of a composite object. 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 ;-)


=== 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)
c1 = C() ; c2 = C()
c1.x = 1        # change x for c1 only
c1.a = 'v'      # change a for c1 only
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
c1.a = 'v'      # change a for c1 only
print c1,c2     # ==> C(1,0,v) C(1,0,u)


Denis
________________________________

la vita e estrany

http://spir.wikidot.com/
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to