S
S
sswwssww2020-07-25 13:05:31
Python
sswwssww, 2020-07-25 13:05:31

Why is __set__ called on assignment?

There is the following code:

class NonNegative:
    def __init__(self, name):
        self.name = name

    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if value < 0:
            raise ValueError('Cannot be negative.')
        instance.__dict__[self.name] = value

class Order:
    price = NonNegative('price')

    def __init__(self, name, price, quantity):
        self._name = name
        self.price = price

apple_order = Order('apple', 1, 10)
apple_order.price = -10

-I look through the dabagger, when the line " self.price = price " is executed, there is a transition to " __set__ " of the " NonNegative " class . Why is this happening? We don't use the " price " instance of " NonNegative " in any way. As far as I understand " self.price " in self.price = price is just an instance field of the " Order " class.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sswwssww, 2020-07-25
@sswwssww

Those. apparently, when "self.price" is executed, Python first looks (1) if the instance has such a field, if not, then (2) looks for this field in the class (and we have this field and is a descriptor), if it is not there either then (3) it is simply created. In my case, the stop occurs at the second point.
The whole point is that through self we can access the fields of the class.
javedimka : "In the __ini__ method, self.price is already a descriptor, because self.price is defined at the class level, you don't write 1 there, you call the descriptor's __set__ method during initialization. Try passing -10 during initialization, everything will become clear right away "

R
Roman Kitaev, 2020-07-25
@deliro

Fluent python, chapter on descriptors.

D
Dr. Bacon, 2020-07-25
@bacon

We do not use the "price" instance in any way.

I don't understand why you think so? We use it, it is enough to do print(type(self.price)) and see what is what.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question