简体   繁体   中英

Applying property setter logic in __init__

I read this answer with setting an attribute in python and getting maximum recursion depth error .

How and where should I check and test a value when setting an attribute ? I know I can check it in setter , but is it good to check it in __init__() of an class ? If I check it in __init__() , then my setter and __init__ have repeated code.

Example of my code:

class RealNumber:

    def __init__(self, real):
        self._real = real  # NEED TO TEST IT BEFORE ASSIGNMENT
                           # TEST IS SAME AS IN SETTER

    @property
    def real(self):
        return self._real

    @real.setter
    def real(self, value):
        if isinstance(value, int):
            self._real = value
        else:
            raise ValueError('Can not set real part with value {}'.format(value))

You can simply issue self.real = real in __init__ . The property setter is already in effect.

class RealNumber:
    def __init__(self, real):
        self.real = real

    @property
    def real(self):
        return self._real

    @real.setter
    def real(self, value):
        if isinstance(value, int):
            self._real = value
        else:
            raise ValueError('Can not set real part with value {}'.format(value))


r = RealNumber(3)
print(r._real)
print(r.real)
print(vars(r))

try:
    RealNumber('bogus')
except ValueError:
    print('error as expected')

Output:

3
3
{'_real': 3}
error as expected

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