Intermediate Object-Oriented Programming in Python
Jake Roach
Data Engineer
class Student:
def __init__(self, name, student_id, tuition_balance):
self.name = name
self.student_id = student_id
self.tuition_balance = tuition_balance
# Trying to create a class can be tricky
walker = Student("Sarah Walker", 319921, 15000)
student_id supposed to be an integer?tuition_balance be a float or an integer? Maybe a string?walker has been created, how can we remember what type it is later in code?Optional tool that allows for information about an object to be added to code
typing library, custom classes# Type hinting for declarative logic
name: str = "Frost" # Before: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# Type hinting for function/method definitions
def get_schedule(semester: str) -> dict:
...
variable: typedef .... () -> type: to specify return typeBuilt-in types support generic syntax for type hinting
list, dict, tuple - no imports neededstudent_names: list[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: dict[str, float] = {
"Casey": 3.71,
"Sarah": 4.0
}
typing module: Any, Callable, Iterator, Optionalclass Student:
def __init__(self, name: str, student_id: int, tuition_balance: float) -> None:
self.name: str = name
self.student_id: int = student_id
self.tuition_balance: float = tuition_balance
def get_course(self, course_id: str) -> Course:
...
return course
# Use Student and Course to type hint
walker: Student = Student("Sarah Walker", 319921, 15000)
data_science: Course = walker.get_course("TDM-20100")
# walker: Student = Student("Sarah Walker", 319921, 15000)
print(type(walker))
<class '__main__.Student'>
# data_science: Course = walker.get_course("TDM-20100")
print(type(data_science))
<class '__main__.Course'>
Intermediate Object-Oriented Programming in Python