0

I have this code:

class Human(object):

    def __init__(self, amount):
        self._age = self.age = amount

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, amount):
        if amount > 50:
            self._age = amount
       else:
            print('You are too young')

What I am wondering about is, is that a viable way to make the argument passed to __init__ pass through some sort of logic implemented in the property ? I browsed through a lot of answers here and read the documentation, and still I couldn't find any mention about such a thing. The code is working as intended when creating a test instance of the class:

bob = Human(30)

yields the proper warning. Attempting to set the name property afterwards does too, and when given a proper argument (in this case any number > 50) everything seems to work as intended. Is there some sort of caveat about this and if yes, what is the most Pythonic way to approach this problem?

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • 3
    Why not just `self.age = amount` in `__init__`? You shouldn't just `print` if the value is invalid, you should throw a `ValueError`. – jonrsharpe Jul 16 '17 at 13:07
  • 1
    Why the down vote? – cs95 Jul 16 '17 at 13:20
  • @cᴏʟᴅsᴘᴇᴇᴅ My guess is it's because the OP didn't bother to explain why they're using a double assignment when `self.age = amount` is the obvious way to do this. "Is it a good idea to write needlessly verbose code for an unspecified reason?" isn't exactly a good question. – Aran-Fey Jul 16 '17 at 13:29
  • With this code, regardless of what the setter for `age` does, `self._age` is going to be assigned the value `amount`. Is that what you want? – chepner Jul 16 '17 at 13:44

0 Answers0