[Tutor] set/getattr and inheritance
Run-Sun Pan
runsun@bilbo.bio.purdue.edu
Fri, 5 Oct 2001 14:00:03 -0500 (EST)
Hi all,
I am using the __setattr__ and __getattr__ pair
to access variables of my class:
#-------------------------
class c_template():
myAddr = 'blahblahblah'
class c_myclass(c_template):
def __init__(self):
self.__dict__['vars']={}
self.vars['myName']='pan'
def __setattr__(self,name,value):
if not self.vars.has_key(name): raise AttributeError
self.vars[name]=value
def __getattr__(self,name):
if not self.vars.has_key(name): raise AttributeError
return self.vars[name]
mc = c_myclass()
mc.myName='panpan'
mc.myAddr='blah' # trying to use the var of ancestor c_template
#---------------------------
The last line of code raises an AttributeError. It's
quite obvious that this .myAddr is not in the "vars"
variable list of the current class (c_myclass), thus
an error occurs.
I can overcome this by redefining the c_myclass as:
class c_myclass(c_template):
def __init__(self):
myName='pan'
or simply:
class c_myclass(c_template):
myName='pan'
which means, bypassing the usage of __setattr__,
__getattr__ pairs. But then I can't utilize their
functions to check the input values before they
are assigned / obtained.
Is there anyway to use these setattr/getattr pair
yet still be able to access ancestor's variables ?
thx in advance.
pan