En Mon, 31 Dec 2007 16:01:38 -0200, <[EMAIL PROTECTED]> escribi�: > Thanks you Gabriel and Timm for your thoughtful responses. I am very > appreciative. > > I had heard about the properties function, but wanted to understand > the old syntax first before I tried that. Thanks to your responses, I > was able to see what the problem was. > > Here is a solution I came up with: > > class Person(): > def __init__(self, fName="", lName=""): > self.__fName = fName > self.__lName = lName > > def __getattr__(self, attr): > if attr == "name": > return self.__fName + " " + self.__lName > else: > return self.__dict__[attr] > > def __setattr__(self, attr, value): > # this assumes that value is a tuple of first and last name > if attr == "name": > self.__fName, self.__lName = value > else: > self.__dict__[attr] = value >
Almost. __getattr__ is called *after* searching the name in the standard places, including self.__dict__, so there is no point in looking there again as it will fail certainly (with a KeyError instead of the right AttributeError). def __getattr__(self, attr): if attr == "name": return self.__fName + " " + self.__lName raise AttributeError, attr (__getattr__ and __setattr__ despite their names, are not very symmetrical) > To be honest, I think the above old syle (I guess) method is pretty > cool and elegant. If you have one or two special attributes, may be fine. But when you want to define many properties, it becomes unmanageable. And notice that the mere existence of those methods slows down A LOT *all* attribute accesses, not just the ones related to your special names. > Thanks again and have a GREAT NEW YEAR!! You too! -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list