overriding a property

John Posner jjposner at optimum.net
Tue Oct 19 10:49:50 EDT 2010


On 10/19/2010 9:39 AM, Lucasm wrote:
> Hi,
>
> A question. Is it possible to dynamically override a property?
>
> class A(object):
>      @property
>      def return_five(self):
>          return 5
>
> I would like to override the property for an instance of A to say the
> string 'bla'.

Is this the sort of thing you're looking for ...

#-------------------------------------
import inspect

class A(object):
     @property
     def return_five(self):
         try:
             # get name of this function ...
             frm = inspect.getframeinfo(inspect.currentframe())
             # ... and use it as dict key
             return self.__dict__[frm.function]

         except KeyError:
             # attr not set in instance
             return 5

a = A()
print "one:", a.return_five

b = A()
b.__dict__['return_five'] = 'bla'
print "two:", b.return_five

c = A()
print "three:", c.return_five
#-------------------------------------

The output is:

   one: 5
   two: bla
   three: 5

If you don't want to fool around with the inspect module, you can 
hard-code the function name as the instance's dict key:

    return self.__dict__['return_five']

HTH,
John



More information about the Python-list mailing list