简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM