Classes
Contents
1.4.3. Classes#
Classes provide a way to define templates to bundle data and functionality together.
1.4.3.1. Class Definition Syntax#
A Python class is defined as follow:
class ClassName:
<statement-1>
.
.
.
<statement-N>
The statements defining a class are either class attributes or methods.
A class constructor is defined by overriding the __init__
method.
The self
keyword is used to reference to an object variables. Instance methods of the class should start with the self
parameter.
from typing import Generator
class ConcordiaPerson:
"""Define people at Concordia University."""
def unique_id() -> Generator[str, None, None]:
"""Yield a unique Concordia ID.
Yields
------
Generator[str, None, None]
Concordia ID.
"""
id_ = 1
while True:
yield str(id_).zfill(8)
id_ +=1
school: str = "Concordia University"
id_generator: Generator[str, None, None] = unique_id()
holidays: list[str] = ["Winter Break"]
def __init__(self, department: str, name: str):
"""Initialize the information for the Concordia person.
Parameters
----------
department : str
School department the person is part of.
name : str
Name of the person.
"""
self.department = department
self.name = name
self.id_ = next(self.id_generator)
def get_info(self) -> str:
"""Get information on the Concordia person.
Returns
-------
str
Information on Concordia Person.
"""
return f"{self.name} (ID: {self.id_}) is from the {self.department} department at {self.school}."
1.4.3.2. Class Objects#
We can create an object from the class by instantiating it.
Afterwards, we will be able to call the class methods and access or modify the object attributes.
# We instantiate two objects.
concordia_people = [
ConcordiaPerson("Computer Science", "Alice"),
ConcordiaPerson("Software Engineering", "Bob"),
]
for person in concordia_people:
print(person.get_info())
Alice (ID: 00000001) is from the Computer Science department at Concordia University.
Bob (ID: 00000002) is from the Software Engineering department at Concordia University.
1.4.3.2.1. Class vs. Object Attributes#
While object attributes are independent of the different class instances, class attributes are shared for all instance of the class.
# Class attributes
concordia_people[0].holidays.append("Fall Break")
for person in concordia_people:
print(person.holidays)
['Winter Break', 'Fall Break']
['Winter Break', 'Fall Break']
# Object Attributes
concordia_people[0].name = "Charlie"
for person in concordia_people:
print(person.get_info())
Charlie (ID: 00000001) is from the Computer Science department at Concordia University.
Bob (ID: 00000002) is from the Software Engineering department at Concordia University.
1.4.3.3. Inheritance#
Python classes support inheritance and multiple inheritance.
We only discuss simple inheritance in this tutorial. The reader can refer to Python Inheritance Tutorial for details on multiple inheritance.
The super()
method provides access to the parent class.
class ConcordiaStudent(ConcordiaPerson):
def __init__(self, department: str, name: str, courses: list[str]):
"""Initialize the information for the Concordia student.
Parameters
----------
department : str
School department the student is part of.
name : str
Name of the student.
list : list[str]
Courses registered in.
"""
super().__init__(department, name)
self.courses = courses
def registered_courses(self) -> str:
"""Get the information on registered courses for the student.
Returns
-------
str
Description of the courses taken by the student.
"""
return (
f"{self.name} (ID: {self.id_}) are registered for these courses:"
+ ("\n- ".join([""] + self.courses))
)
class ConcordiaTeacher(ConcordiaPerson):
def __init__(self, department: str, name: str, courses: list[str]):
"""Initialize the information for the Concordia teacher.
Parameters
----------
department : str
School department the teacher is part of.
name : str
Name of the teacher.
list : list[str]
Courses teaching.
"""
super().__init__(department, name)
self.courses = courses
def teaches(self) -> str:
"""Get the information on courses taught by the teacher.
Returns
-------
str
Description of the courses taught by the teacher.
"""
return (
f"{self.name} (ID: {self.id_}) teaches these courses:"
+ ("\n- ".join([""] + self.courses))
)
teacher = ConcordiaTeacher("CS", "Charlie", courses=["comp 101"])
students = [
ConcordiaStudent("CS", "Alice", courses=["comp 101", "comp 203"]),
ConcordiaStudent("CS", "Bob", courses=["comp 101", "comp 205"]),
]
print("="*15, "Teacher", "="*15)
print(f"""
{teacher.get_info()}
{teacher.teaches()}
"""
)
print("="*15, "Students", "="*15)
for student in students:
print(f"""
{student.get_info()}
{student.registered_courses()}
"""
)
=============== Teacher ===============
Charlie (ID: 00000003) is from the CS department at Concordia University.
Charlie (ID: 00000003) teaches these courses:
- comp 101
=============== Students ===============
Alice (ID: 00000004) is from the CS department at Concordia University.
Alice (ID: 00000004) are registered for these courses:
- comp 101
- comp 203
Bob (ID: 00000005) is from the CS department at Concordia University.
Bob (ID: 00000005) are registered for these courses:
- comp 101
- comp 205