A
A
albertalexandrov2018-09-14 15:13:38
Python
albertalexandrov, 2018-09-14 15:13:38

Descriptor application?

Hey!
How justified is the use of the descriptor here? Or you can solve the problem of checking the price and quantity attributes for 'positivity' in another way. Example taken from https://dev.to/dawranliou/writing-descriptors-in-p... .

class NonNegative:

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

    def __set_name__(self, owner, name):
        self.name = name


class Order:
  
    price = NonNegative()
    quantity = NonNegative()

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

    def total(self):
        return self.price * self.quantity

apple_order = Order('apple', 1, 10)
apple_order.price = -10  # ValueError: Cannot be negative

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arsen Abakarov, 2018-09-14
@ArsenAbakarov

i would use property.setter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question