简体   繁体   中英

property: call setter in init()

I have a simple class like this:

class TestVolume:

    def __init__(self, volume: float):

        self._volume = volume * 1000
        self.volume = self._volume


    @property
    def volume(self):
        return self._volume / 1000


    @volume.setter
    def volume(self, value):
        if value <= 0:
            raise ValueError("Volume must be > 0")
        self._volume = value

Basically, I instantiate a TestVolume object with a volume, which should always be a positive float.

I want the volume attribute to be a property of the class. But I also want to check the volume when the object is created. Is it the right way to do it ?

The setter is the (for the most part) the only method that needs to modify _volume directly. Just use the property in __init__ ; whether or not you try to catch the ValueError that the setter might raise is up to you.

def __init__(self, volume: float):
    try:
        self.volume = volume * 1000
    except ValueError:
        self.volume = 0

Here, __init__ is exercising a policy of converting a negative volume to 0 when the object is created; other users of the setter can decide for themselves what to do in the event of an exception.

Your code is correct, but it won't work for creation of new objects. I'm not familiar with a way of accessing @property at __init__ . (Python 2.7) What you can do, is inserting an assert statement. It will throw an error if the user input is invalid. You can enclode this in try.. catch block if you want to set a default value.

class TestVolume:

    def __init__(self, volume: float):
        assert volume > 0
        self._volume = volume * 1000
        self.volume = self._volume

And the rest of your code stays the same.

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