mardi 20 novembre 2018

How to check value before assignment 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))

Aucun commentaire:

Enregistrer un commentaire