[Q] Accessors...
Olivier Deckmyn
olivier.deckmyn at mail.dotcom.fr
Tue Jul 20 03:00:30 EDT 1999
More information about the Python-list mailing list
Tue Jul 20 03:00:30 EDT 1999
- Previous message (by thread): [Q] Accessors...
- Next message (by thread): [Q] Accessors...
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Thanx A LOT greg :) I had started to code such a system after reading the "Getters and Setters" thread in this newsgroup (1999/07/15) Have a nice day. Greg Ewing <greg.ewing at compaq.com> a écrit dans le message : 37939CC2.BD5A1AC9 at compaq.com... > Olivier Deckmyn wrote: > > > > This way, because it exists two methods get_XXX and set_XXX, a special > > proporty XXX would be implicitly created, and would make the user call > > "automatically" the get/set methods. > > Yes, there is a way. If a class has a method > called __getattr__, it is automatically called > whenever you try to get the value of an attribute > which doesn't exist. So you can do something like > > class AutoAccess: > > def __getattr__(self, name, *args, **kw): > return apply(getattr(self, "get_"+name), args, kw) > > then any class which inherits from AutoAccess will > have any attempt to get a non-existent XXX attribute > redirected to a get_XXX method. (Note that the above > implementation is a bit simplistic -- it will enter an > infinite loop if there is no get_XXX method defined > in the class.) > > There is a corresponding feature for setting an > attribute: if there is a __setattr__ method, it gets > called on every attempt to set the value of an > attribute, so you can do > > def __setattr__(self, name, value): > try: > setter = getattr(self, "set_"+name) > except AttributeError: > setter = None > if setter: > setter(value) > else: > self.__dict__[name] = value > > This is more complicated because the __setattr__ > method, if present, is called *before* checking > whether the attribute exists (by necessity, since > setting an attribute which doesn't already exist > is perfectly legal). Hence the code to catch the > case where there is no set_XXX method and set the > attribute directly. > > As you can see, what you are asking for can be > done, but it is expensive -- attribute access > through these methods will be considerably slower > than just calling get_XXX and set_XXX methods > directly. You'll have to decide whether it's > worth the price in your application. > > Warning: The above code is for illustration > purposes only -- I haven't tested it! > > Greg
- Previous message (by thread): [Q] Accessors...
- Next message (by thread): [Q] Accessors...
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list