tags:

views:

172

answers:

1

I am trying to understand what Python's descriptors are and what they can useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code:

>>> 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()
  1. Why do I need the descriptor class? Please explain using this example or the one you think is better.

  2. What is instance and owner here? (in __get__). So my question is, what is the purpose of the third parameter here?

  3. How would I call/ use this example?

Sorry for being such a noob, but I can't really understand how to get this working.

+3  A: 

The descriptor is how python's property type is implemented. A descriptor simply implements __get__, __set__, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example

temp=Temperature()
temp.celsius #calls Celsius.__get__

Accessing the property you assigned the descriptor to (celsius in the above example) calls the appropriate descriptor method.

instance in __get__ is the instance of the class (so above, __get__ would recieve temp, while owner is the class with the descriptor (so it would be Temperature).

You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class.

An article about descriptors can be found at http://martyalchin.com/2007/nov/23/python-descriptors-part-1-of-2/

EDIT: As jchl pointed out in the comments, if you simply try Temperature.celsius, instance will be None.

l33tnerd
@l33tnerd: Thanks for the information, I will read up the article.
Matt Bronson
@l33tnerd: What is the difference between a `property` and a `descriptor` class?
Matt Bronson
@Matt: A property is a kind of descriptor; it has `__get__` and `__set__` methods. If Python did not give you the property decorator, you could still implement it on your own by defining a class with `__get__` and `__set__` methods.
unutbu
To clarify something said in this answer: `instance` in `__get__` will be `None` if you access the descriptor via the class (i.e. `Temperature.celsius`).
jchl