Tito C Tito C - 2 months ago 11
Python Question

How can I use descriptors for non-static methods?

I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.

If I have

Normal use, considering that the method(param) returns an object

class SomeClass():
property = method(param)


I can then do:

instance = SomeClass()
instance.property = 3


and be able to have that setting handled by the the class of which property is an instance.

Now, if I instead have

class SomeClass():
def__init__(self):
self.property = method(param)


and I do:

instance = SomeClass()
instance.property = 3


That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.

Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?

Python version: 2.7

Thanks!

Answer

Considering method(param) returns a descriptor, you may invoke it manually with a property like so:

class SomeClass(object):

    def __init__(self):
        self._descriptor = method(param)

    @property
    def my_attribute(self):
        return self._descriptor.__get__(self, self.__class__)

    @my_attribute.setter
    def my_attribute(self, value):
        self._descriptor.__set__(self, value)

This will allow you to create instance-specific descriptors instead of class-level descriptors.

I still do not see the reason for you to do that as descriptors should usuallty be class-level. That's their point. Else they are just regular objects which you can call using properties.