Connecting Tech Pros Worldwide Forums | Help | Site Map

Class Variables (Python 2.2/2.3)

srijit@yahoo.com
Guest
 
Posts: n/a
#1: Jul 18 '05
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

Peter Otten
Guest
 
Posts: n/a
#2: Jul 18 '05

re: Class Variables (Python 2.2/2.3)


srijit@yahoo.com wrote:
[color=blue]
> 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?[/color]

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
Peter Otten
Guest
 
Posts: n/a
#3: Jul 18 '05

re: Class Variables (Python 2.2/2.3)


srijit@yahoo.com wrote:
[color=blue]
> 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?[/color]

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
Closed Thread