Lost in descriptor land

Ankush Thakur ankush.thakur53 at gmail.com
Thu Jun 30 21:06:00 EDT 2016


Hello,

There's something I don't understand about descriptors. On a StackOverflow discussion (http://stackoverflow.com/questions/12846116/python-descriptor-vs-property) one of the answers provides the following descriptors example:

class Celsius( object ):
    def __init__( self, value=0.0 ):
        self.value= float(value)
    def __get__( self, instance, owner ):
        return self.value
    def __set__( self, instance, value ):
        self.value= float(value)

class Temperature( object ):
    celsius= Celsius()
    farenheit= Farenheit()

... and then gets chided in the comments:

"I believe your descriptor implementation of celsius is not correct. You should have set the celsius on instance rather than self; If you create two Temperature objects they will share the same celsius value."

Overall, I have two problems:
1) I don't get the idea behind the 'instance' and 'owner' parameters at all. Is there some simple tutorial that can explain these?
2) I don't understand the motivation behind the comment. Of course declaring a class variable would cause celcius to be the same for all objects. Shouldn't we be instead using self.celcius in, say, __init__() and then everything will work fine?

I have seen examples (http://programeveryday.com/post/an-introduction-to-python-descriptors/) where "instance" is used as keys of a dictionary, but given my argument above, isn't this approach an overkill?

Regards,
Ankush Thakur



More information about the Python-list mailing list