overriding a property

Lucasm lordlucraft at gmail.com
Wed Oct 20 10:12:33 EDT 2010


On 20 Okt, 16:09, Peter Otten <__pete... at web.de> wrote:
> Lucasm wrote:
> > On 19 Okt, 18:28, Steven D'Aprano <st... at REMOVE-THIS-
> > cybersource.com.au> wrote:
> >> On Tue, 19 Oct 2010 06:39:56 -0700, 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'.
> >> >>> class A(object):
>
> >> ...     _five = 5  # class attribute shared by all instances
> >> ...     @property
> >> ...     def return_five(self):
> >> ...         return self._five
> >> ...
>
> >> >>> a = A()
> >> >>> a._five = 'bla'  # set an instance attribute
> >> >>> b = A()
> >> >>> print a.return_five
> >> bla
> >> >>> print b.return_five
>
> >> 5
>
> >> --
> >> Steven
>
> > Thanks for the answers. I would like to override the property though
> > without making special modifications in the main class beforehand. Is
> > this possible?
>
> You can dynamically change the instance's class:
>
> >>> class A(object):
>
> ...     @property
> ...     def five(self): return 5
> ...>>> a = A()
> >>> b = A()
> >>> class B(type(b)):
>
> ...     @property
> ...     def five(self): return "FIVE"
> ...>>> b.__class__ = B
> >>> a.five
> 5
> >>> b.five
>
> 'FIVE'
>
> But still -- what you are trying looks like a bad idea. What's your usecase?
>
> Peter

Thanks for your answer. That's exactly the thing I'm doing right now
and it works :) My use case is testing. I want to test a class and
reduce the complexity of the output generated by certain properties.
It would be nice to know alternatives to this approach.



More information about the Python-list mailing list