Is there a better way of coding this?

Edward C. Jones edcjones at erols.com
Tue Jun 3 05:16:40 CEST 2003


Anders J. Munch wrote:

> # very much untested code follows:
> def makeprop(getname, truename, funnanme):
>     def fget(self):
>         # Subtle error processing here.
>         setattr(self, truename, getattr(self, funname)(self.data))
>         return getattr(self, truename)
>     return property(fget, None, None)
> 
> class X(object):
>     i = makeprop('geti', '_i', 'Fgeti')
>     ...

Here is a working version:

def makeprop(truename, funname):
     def fget(self):
         setattr(self, truename, getattr(self, funname)())
         return getattr(self, truename)
     return property(fget, None, None)

class X(object):
     i = makeprop('_i', 'Fi')

     def __init__(self, k):
         self.k = k

     def Fi(self):
         return self.k

x = X(11)
print x.i

Thanks for the help,
Ed Jones





More information about the Python-list mailing list