Extra Topic: Properties


Note: extra topics are not in CS Academy, but are required and can appear on any future homework, writing session, quiz, or exam.
Getting Started
Example: Data Validation:

class Person: def __init__(self, name, age): self.name = name self._age = age # <-- this is a hidden instance variable def __repr__(self): return f'Person({repr(self.name)}, {self._age})' @property def age(self): # This is the getter method, which here just returns the hidden variable return self._age @age.setter def age(self, value): # This is the setter method, where we do the data validation if value < 0: raise ValueError("A person's age must not be negative.") self._age = value p = Person('John Doe', 32) print(p) # Person('John Doe', 32) print(p.name) # John Doe print(p.age) # 32 p.age = 33 print(p.age) # 33 p.age = -5 # ValueError: A person's age must not be negative.

Example: Computed Properties:

class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f'Person({repr(self.name)}, {self.age})' @property def firstName(self): # This is the computed property (we do not store the first name, # but rather we compute it on-demand on each call): return self.name.split(' ')[0] p = Person('John Doe', 32) print(p) # Person('John Doe', 32) print(p.name) # John Doe print(p.age) # 32 print(p.firstName) # John (this is a computed property)