Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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 "
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question