Class Variables (Python 2.2/2.3)

S

srijit

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?

Regards,
Srijit
 
P

Peter Otten

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top