0

I am having a small code that define a class with one property. Then when I expect in the main program for the prints, they don't happen and the result for the above code is '5':

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        print 'getter'
        return self._x

    @x.setter
    def x(self, x):
        print 'setter'
        self._x = x


def main():
    C.x = 5
    print C.x


if __name__ == '__main__':
    main()

My question is what can I do to make this code print the 'getter' and the 'setter'?

Yotam Hammer
  • 127
  • 1
  • 2
  • 8

1 Answers1

1

If you'd use C properly (ie create an instance of it) you will get what you expect:

c = C()
c.x = 5
print(c.x)

outputs

setter
getter
5
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 2
    Oh, huh, they've got that problem too. They do also need to inherit from `object`, though; the `print` syntax indicates they're on Python 2. – user2357112 Dec 19 '18 at 17:47
  • If I use it like this there is an overhead? – Yotam Hammer Dec 19 '18 at 17:52
  • 2
    @YotamHammer: Overhead compared to what? The code you've posted that doesn't work? Don't compare the performance of correct code and wrong code; you can do anything as fast as you want if you're fine with doing it wrong. – user2357112 Dec 19 '18 at 17:56
  • You are right, is there a more convenient way to change the behavior of the setters and the getters of objects? – Yotam Hammer Dec 19 '18 at 17:57