简体   繁体   中英

Python: property and setters

I'm writing some code for library, but I'm not sure, whether it is efficiency or not. I should set variables like roll, pitch, yaw, throttle. do I have to write all property and setter? is it best way?

@property
def roll(self):
    return self._roll

@roll.setter
def roll(self, value):
    if(not isinstance(value, int)):
        print("You should put the integer number!")
        value = int(value)

    if value > 100:
        value = 100
    elif value < -100:
        value = -100

    self._roll = value

I'm writing some code for library, but I'm not sure, whether it is efficiency or not. I should set variables like roll, pitch, yaw, throttle. do I have to write all property and setter? is it best way?

First off, be careful with trying to optimize your code too early. More often than not what actually happens when someone attempts to optimize their code, is that they introduces unnecessary bugs into their program. This is not to say that you should never optimize your code. When their is clearly room to restructure your code for efficiency, do so. But avoid trying to be overly 'clever' and blindly 'optimizing' things that aren't apparent.

With all that said, your code looks fine. You're using property exactly as it should be used; To do extra, necessary work during getting and settings of attributes (often more so with setting), without the verbosity of forcing users of your class to use method calls. Don't concern yourself to much with efficiency. As long as your not doing something blatantly inefficient, your fine. As @match said in the comments, using property is more about providing maintainability, stability, and readability, than efficiency.

However, there are severals small areas where you're code could be improved. Namely your type and bounds checking. You can extract this into a separate method and call it where needed:

def _check_value(value):
    try:
        value = int(value)
    except ValueError as err:
        raise ValueError('only integer values are permitted') from err

    if value > 100:
        return 100
    elif value < -100:
        return -100
    return value

@property
def roll(self):
    return self._roll

@roll.setter
def roll(self, value):
    self._roll = self._check_value(value)

@property
def pitch(self):
    return self._pitch

@pitch.setter
def pitch(self, value):
    self._pitch = self._check_value(value)

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