Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property setter in __init__ method?

I have this hypothetical situation where I need to check if a Phone instance is being created with price less than 100 and, if it is, then I have to warn the user that price cannot be less than 100.

I am using the below for this example:

class Phone(object):
    def __init__(self,v):
        self._cost = v

    @property
    def cost(self):
        return self._cost

    @cost.setter
    def cost(self,value):
        if value < 100:
            print("Cost cannot be less than 100")
        else:
             self._cost = value

s8 = Phone(98)

But this code is not letting the user know that a phone cannot be created with price less than 100. What is the use of having a setter function for a property in Python if we cannot check the values when we are initializing the object? Am I doing anything wrong here?

like image 650
karun_r Avatar asked Oct 21 '25 11:10

karun_r


1 Answers

You're not actually calling the property setter. You're directly setting the "private" variable.

If you want to warn the user, you need to do:

def __init__(self,v):
    self.cost = v

Remember, a property allows you to abstract away internal implementation details (cost, in this way, is the public interface for _cost). However, if you directly manipulate _cost yourself, then your interface will not warn the user during initialization.

like image 197
Alexander Huszagh Avatar answered Oct 25 '25 11:10

Alexander Huszagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!