Dynamically Defined Functions in Classes?

Jan Dries jdries at mail.com
Wed Jan 31 11:56:21 EST 2001


Jim Meyer wrote:
> I have an application in which I wish to treat the members of a
> dictionary as attributes; that is, I want to use set-and-get functions
> to access them. The {weird|clever|tricky|stupid} thing I want to do is
> to dynamically define the access functions at the time that an instance
> of the class is initialized. Here's a brief example
> 
> defaultFoo = {'joe' : 'cool', 'frank' : 'lee', 'ron' : 'dell'}
> 
> class Bar :
>   def __init__(self) :
>     self.Foo = defaultFoo
>     for key in self.Foo :
>       # Define function member key(self,value) which is equivalent
>       # to calling self.setOrGet(key,value), e.g def joe(value) : ...
> 
>   def setOrGet(self, attrName, value = None) :
>     if value == None :
>       return self.Foo[attrName]
>     else :
>       self.Foo[attrName] = value
>       return self.Foo[attrName]
> 
> Any elegant way to go about this? Or smarter ways to deal with
> attributes?

Try this:

defaultFoo = {'joe' : 'cool', 'frank' : 'lee', 'ron' : 'dell'}

class Bar:
    def __init__(self):
        self.__foo = defaultFoo
			
    def __getattr__(self,name):
        try:
            return self.__foo[name]
        except:
            raise AttributeError
			
    def __setattr__(self,name,value):
        if name == "_Bar__foo":
            self.__dict__[name] = value
        else:
            try:
                self.__foo[name] = value
            except:
                raise AttributeError
        
You can then write:

    x = Bar()
    print x.joe
    x.frank = "something"

etc.

Regards,
Jan




More information about the Python-list mailing list