This Python Class Properties lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A property looks like an attribute and runs a method. Use it when reading a value needs a calculation or a check.
The @property decorator sits above the method. Callers use object.name, not object.name().
Example 1: Start here
A property is a good fit for a derived value. It is a poor place for a slow network call.
class Course: # a template for objects
def __init__(self, hours): # runs when you create the object
self.hours = hours # store this on the object
@property # extra behavior for the next function
def days(self): # define the function; it runs when you call it
return self.hours / 8 # send this value back to the caller
print(Course(24).days)
Example 2: A computed property
A property is used like an attribute, without parentheses.
class Course: # a template for objects
def __init__(self, seats): # runs when you create the object
self.seats = seats # store this on the object
@property # extra behavior for the next function
def label(self): # define the function; it runs when you call it
return str(self.seats) + " seats" # send this value back to the caller
print(Course(24).label)
Example 3: A guarded setter
The setter refuses a negative number by storing 0 instead.
class Course: # a template for objects
def __init__(self, seats): # runs when you create the object
self._seats = 0 # store this on the object
self.seats = seats # store this on the object
@property # extra behavior for the next function
def seats(self): # define the function; it runs when you call it
return self._seats # send this value back to the caller
@seats.setter # extra behavior for the next function
def seats(self, value): # define the function; it runs when you call it
self._seats = max(0, value) # store this on the object
print(Course(-5).seats)
Example 4: A plain attribute is enough
Use a property only when reading or writing needs extra rules.
class Course: # a template for objects
def __init__(self, title): # runs when you create the object
self.title = title # store this on the object
print(Course("Python").title)
