3

I've been trying to wrap my head around the @property decorator, and I think I get it, but I am very curious to know which magic methods @property (and the builtin property) modify. Is it just __get__ and __set__, or could __getattr__ and __setattr__ be invoked as well? __getattribute__? __setattribute__?

As I understand it, @someproperty will modify __get__, @someproperty.setter will modify __set__, and @someproperty.deleter will modify __del__ but I'm suspicious that I have an over simplified view on this.

I haven't been able to find this information, and I've been searching all day about properties, so hopefully someone can shed some light on this for me. Links and examples greatly appreciated.

edit: I wrongly was saying "call" instead of "modify," I know @property will modify magic methods. I'm just worn out from staring at this forever... thanks for the correction.

Aaron
  • 2,344
  • 3
  • 26
  • 32

2 Answers2

3

@property doesn't call any of those. It defines how they work. Accessing the property then calls __get__, __set__, or __delete__.

class Foo(object):
    @property
    def x(self):
        return 4

    # If the class statement stopped here, Foo.x would have a __get__ method
    # that calls the x function we just defined, and its __set__ and __delete__
    # methods would raise errors.

    @x.setter
    def x(self, value):
        pass

    # If the class statement stopped here, Foo.x would have usable __get__ and
    # __set__ methods, and its __delete__ method would raise an error.

    @x.deleter
    def x(self):
        pass

# Now Foo.x has usable __get__, __set__, and __delete__ methods.

bar = Foo()
bar.x      # Calls __get__
bar.x = 4  # Calls __set__
del bar.x  # Calls __delete__
user2357112
  • 260,549
  • 28
  • 431
  • 505
2

The answer to your title question: __get__(), __set__() and __delete__(),

You will find more detail on the internal workings of property here and, as has been pointed out by dm03514, here

Community
  • 1
  • 1
Mike Vella
  • 10,187
  • 14
  • 59
  • 86