Getters and Setters

Bernhard Herzog herzog at online.de
Thu Jul 15 06:20:54 EDT 1999


"Tim Peters" <tim_one at email.msn.com> writes:

> Oops!  Almost forgot the code!  Dump _Getter.  Dump _Setter.  Have the mixin
> class build the obvious function for what you're after, and add that
> directly to self as an attribute.  Then there's no mixin overhead at all
> after the first time a set/get method is invoked for an instance.  Downside:
> generates many function objects.  Possible alternative:  plug synthesized
> get/set functions into the class object instead; a little slower, but less
> proliferation of function objects.

Hmm. Unfortunately,...

> class GetterSetter:
>     def __getattr__(self, name):
>         if name[:3] == "get":
>             def getter(d=self.__dict__, key=name[3:]):
>                 return d[key]
>             setattr(self, name, getter)
>             return getter

..this introduced a circular reference.

So, putting the functions into the class would be better:

              def getter(self, key=name[3:]):
                  return getattr(self, key)
              setattr(self.__class__, name, getter)
              return getattr(self, name)

>         elif name[:3] == "set":
>             def setter(value, d=self.__dict__, key=name[3:]):
>                 d[key] = value
>             setattr(self, name, setter)
>             return setter

Same here.

>         else:
>             raise AttributeError(name)

[snipped rest of code]




-- 
Bernhard Herzog	  | Sketch, a python based drawing program
herzog at online.de  | http://www.online.de/home/sketch/




More information about the Python-list mailing list