Use Python @propery for value validation



examples/classes/person/person5.py
from datetime import datetime
class Person():
    def __init__(self, years):
        self.age =  years

    @property
    def age(self):
        return datetime.now().year - self.birthyear

    @age.setter
    def age(self, years):
        if years < 0:
            raise ValueError("Age cannot be negative")
        self.birthyear = datetime.now().year - years

examples/classes/person/person5_good.py
from person5 import Person

p = Person(19)
print(p.age)       # 19

p.age = p.age + 1
print(p.age)       # 20

p.birthyear = 1992
print(p.age)       # 28
   # warning: this will be different if you run the example in a year different from 2020 :)

examples/classes/person/person5_bad_init.py
from person5 import Person

print("Hello")

p = Person(-1)

Hello
Traceback (most recent call last):
  File "person5_bad_init.py", line 5, in <module>
    p = Person(-1)
  File "/home/gabor/work/slides/python-programming/examples/classes/person/person5.py", line 4, in __init__
    self.age =  years
  File "/home/gabor/work/slides/python-programming/examples/classes/person/person5.py", line 13, in age
    raise ValueError("Age cannot be negative")
ValueError: Age cannot be negative


Hello
10
Traceback (most recent call last):
  File "person5_bad_setter.py", line 7, in <module>
    p.age = -1
  File "/home/gabor/work/slides/python-programming/examples/classes/person/person5.py", line 13, in age
    raise ValueError("Age cannot be negative")
ValueError: Age cannot be negative