1

In Objective-C, the following code appears to be setting myobj.x to 3:

Foo *myobj = [[Foo alloc] init];
myobj.x = 3;
NSLog(@"%d", myobj.x);

However, it's possible that Foo implements a setter function for x which would intercept this action, setting x to 4, for example. The same goes for reads from x: code that appears to simply be reading the value of x may actually be hitting a getX function in Foo.

Is it possible to do the same in python? When executing the following code:

myobj = Foo()
myobj.x = 3
print myobj.x

Is there some way that myobj.x is actually set to 4? Or is it possible that the print statement displays a 4 due to a nefarious getter implemented in Foo?

Robz
  • 1,747
  • 5
  • 21
  • 35
  • 2
    Yes: Python [properties](http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters) (or more generally [descriptors](http://docs.python.org/2/howto/descriptor.html)) do this. They're usually not "nefarious," though. :) – Danica Aug 22 '13 at 19:40

1 Answers1

2

You can use a property - why you would want to do this is beyond me though. The following physically sets the value to some value other than intended, you could just modify the value of the getter to return a different value as well.

class Blah(object):
    def __init__(self, value):
        self._value = value
    @property
    def value(self):
        return self._value
    @value.setter
    def value(self, value):
        self._value = value + 1

b = Blah(3)
b.value = 25
print b.value
# 26
Jon Clements
  • 138,671
  • 33
  • 247
  • 280