[Tutor] set/getattr and inheritance
Lloyd Kvam
lkvam@venix.com
Fri, 05 Oct 2001 16:35:10 -0400
You are responsible for managing the "inheritance" issues when you use __getattr__ and __setattr__. __setattr__ is the one that's very hard to get correct. I have cheated and used my own routine, normally called set, as an alternative to writing
__setattr__. This set method then searches for the correct dictionary to use. setattr continues to work with the regular class dictionary.
There may well be smarter solutions.
Run-Sun Pan wrote:
>
> 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
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-443-6155
fax: 801-459-9582