eval of a private attribute

J.Jacob joost_jacob at hotmail.com
Fri Mar 22 05:03:33 EST 2002


Looking at the other posts the other class i did post can be improved
upon.
Here is a class for mixin use with a method getAttribute for 'safe'
access to attributes, maybe somebody can improve on it still ?

# file: GetAttribute.py

class GetAttribute:
    """
    A class for 'safe' access to attributes, see method
    getAttribute().
    """
    def __init__(self):
        "__init__() is here only for demonstration purposes."
        self.__user = "~briner/big/usr.rdb"
        self.public_user = "thatsme_public"
    def getAttribute(self, var):
        """
        Get attribute with name 'var', even if "hidden" behind two
        underscores.
        Return None if no attribute with the name var exists.
        """
        if hasattr(self, var): p = getattr(self, var)
        else:
            try: p = getattr(self, '_%s__%s' % 
                             (self.__class__.__name__, var))
            except AttributeError: p = None
        return p


if __name__ == '__main__':
    p = GetAttribute()
    print p.getAttribute('public_user')	# get a public attribute
    print p.getAttribute('user')        # get a 'private' attribute
    print p.getAttribute('nosuchuser')	# get a nonexisting attribute



More information about the Python-list mailing list