Class Variables (Python 2.2/2.3)

Peter Otten __peter__ at web.de
Sat Aug 23 16:02:45 CEST 2003


srijit at yahoo.com wrote:

> Hello Members,
> I do not see any direct mention of class variables in new style
> classes. Only class methods. Have I missed or is it trivial? If not,
> how to define/implement class variables for new style classes?

>From my practical point of view, there are no differences between old and
new style classes in this respect:

def printThem():
    for t in t1, t2, t3:
        print t.name, "=", t.color
    print

#the same goes for class Test(object): ...
class Test:
    color = "blue"
    def __init__(self, name):
        self.name = name

t1 = Test("t1")
t2 = Test("t2")
t3 = Test("t3")

# class atttribute are accessed like instance attributes
printThem() #blue, blue, blue

# class attributes are shaded by instance attributes, 
# which makes them good default values
t1.color = "red"
printThem() #red, blue blue

# class attributes are not copied on instantiation
Test.color = "green"
printThem() #red, green, green

And now let the experts speak up on the subtler aspects :-)

Peter




More information about the Python-list mailing list