Gevorderde objectgeoriënteerde programmering 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
# Een class maken kan lastig zijn
walker = Student("Sarah Walker", 319921, 15000)
student_id een integer zijn?tuition_balance een float of een integer zijn? Of een string?walker is gemaakt, hoe onthouden we later in de code het type?Optionele tool om info over een object aan code toe te voegen
typing-library, eigen classes# Voeg type hints toe bij het maken van
# een variabele
gpa: float = 3.92
# Voeg type hints toe aan een functie/
# methodedefinitie
def check_grades(year: str) -> List[int]:
...
# Je kunt ook eigen classes gebruiken
students: Dict[str, Student] = {...}
# Type hints voor declaratieve logica
name: str = "Frost" # Voorheen: name = "Frost"
student_id: int = 91031367
tuition_balance: float = 17452.78
# Type hints voor functie-/methodedefinities
def get_schedule(semester: str) -> dict:
...
variable: typedef .... () -> type: om returntype te geventyping is een library met extra tools voor type hints
List, Dict, Tuplefrom typing import List, Dict
student_names: List[str] = ["Morgan", "Chuck", "Anna"]
student_gpas: Dict[str, float] = {
"Casey": 3.71,
"Sarah": 4.0
}
Any, Set, Iterator, Callableclass 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
# Gebruik Student en Course voor type hints
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'>
Gevorderde objectgeoriënteerde programmering in Python