karun_r
karun_r

Reputation: 183

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?

Upvotes: 4

Views: 4756

Answers (1)

Alex Huszagh
Alex Huszagh

Reputation: 14644

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.

Upvotes: 6

Related Questions