puzzlement about classmethod
Faheem Mitha
faheem at email.unc.edu
Sat Jun 24 15:25:29 EDT 2006
Hi,
Consider the following small script.
My understanding of how this works is that, conceptually, class B
holds a separate copy of variable x from class A.
Nearly everything behaves the way I would expect, except that setting
x to 12 in A using class_setx at the beginning also sets the value for
x in B. However, the converse (setting x in B using class_setx), does
not change the value in A, which I would consider to be the expected
behavior.
However, after that the two x variables appear to behave
independently. Can anyone explain to me why this is so?
Regards, Faheem Mitha.
******************************************************************
#!/usr/bin/python
class A(object):
x = 0
def class_getx(cls):
return cls.x
class_getx = classmethod(class_getx)
def class_setx(cls, _x):
cls.x = _x
class_setx = classmethod(class_setx)
def getx(self):
return type(self).x
def setx(self, _x):
type(self).x = _x
class B(A):
pass
def printx():
print "*** begin printing values of x... ***"
print "Fetching from A using class_getx gives %s"%(A.class_getx())
print "Fetching from B using class_getx gives %s"%(B.class_getx())
print "Fetching from A using instance a and getx gives %s"%(a.getx())
print "Fetching from B using instance b and getx gives %s"%(b.getx())
print "*** end printing values of x... ***"
a = A()
b = B()
printx()
print "setting x to 12 in A using class_setx"; A.class_setx(12)
printx()
print "setting x to 15 in B using class_setx"; B.class_setx(15)
printx()
print "setting x to 10 in A using class_setx"
A.class_setx(10)
printx()
print "setting x to 44 in A using instance a and setx"; a.setx(55)
printx()
print "setting x to 22 in B using instance b and setx"; b.setx(22)
printx()
More information about the Python-list
mailing list