Use of lambda functions in OOP, any alternative?

Scott David Daniels scott.daniels at acm.org
Wed May 24 16:37:43 EDT 2006


Pablo wrote:

> Second solution: This is what i want, but...
> 
> class Base(object):
>     def __init__(self, attr):
>         self._attr = attr
>     def getattr(self):
>         return self._attr
>     attr = property(fget=lambda self: self.getattr())
> 
> class Derived(Base):
>     def getattr(self):
>         return 2*self._attr
> 
> Question: Isn't there an *alternative* way to do it without the lambda
> function?
> 
> Thanks in advance!

Simplest:

     class Base(object):
         def __init__(self, attr):
             self._attr = attr
         def getattr(self):
             return self._attr
         @property  # single-arg property is a read-only thing.
         def attr(self):
             return self.getattr()

### Little longer; maybe more explicit (tastes vary):

     class Base(object):
         def __init__(self, attr):
             self._attr = attr
         def getattr(self):
             return self._attr
         def attr(self):
             return self.getattr()
         attr = property(fget=attr)


--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list