Dynamically Defined Functions in Classes?

Jim Meyer purp at wildbrain.com
Wed Jan 31 10:01:01 EST 2001


Hello!

I'm trying to stretch my knowledge of Python and I've run into a brick
wall. I've bought and read several TFMs with no success, but I'm
probably looking in the wrong place.

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?

Thanks!

--j
-- 
Jim Meyer, Geek At Large                              purp at wildbrain.com





More information about the Python-list mailing list