简体   繁体   中英

Access property object (for replacing setter method)

Consider the following code taken from the official documentation

class test:
    _x = 10
    def getx(self): return self._x
    def setx(self, value): self._x = value
    x = property(getx, setx)

as already explained in many other questions, this is 100% equivalent to

class test:    

    _x = 10

    @property
    def x(self):
        return self._x

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

I would like to access the property x (and not the int in _x ) in order to change the value of x.setter .

However doing type(test().x) returns int rather than property indicating that what test().x returns is _x and not the property x . Indeed, trying to do access test().x.setter returns a AttributeError: 'int' object has no attribute 'setter' .

I understand that 99.9% of the time, when someone does test().x he wants to access the value associated with the property x . This is exactly what properties are meant for.

However, how can I do in that 0.01% of the times when I want to access the property object rather than the value returned by the getter ?

x is a class attribute, whose __get__ method receives a reference to the object when invoked on an instance of the class. You need to get a reference to the class first, then you can get the actual property object without invoking the getter.

>>> t = test()
>>> t.x
10
>>> type(t).x
<property object at ....>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM