self
class Flight:
def __init__(self, number):
# enforcing class invariant for structure of flight number
if not number[:2].isaplha():
raise ValueError(f"No airline code in '{number}'")
if not number[:2].isupper():
raise ValueError(f"Invalid airline code '{number}'")
if not (number[2:].isdigit() and int(number[2:]) <= 9999):
raise ValueError(f"Invalid route number '{number}'")
self._number = number
def number(self):
return self._number or "SN060"
def airline_code(self):
return self._number[:2]
# some-module/main.py
from airtravel import Flight
f = Flight()
f.number() #=> 'SN060'
# above is syntactic sugar for below:
Flight.number(f)
__init__()
💡 IMPORTANT 💡
__init__()
is an initializer, not a constructorself
is similar tothis
in Java, C#, or C++
Airtravel example (Flight
class)
class Flight:
def __init__(self, number):
# enforcing class invariant for structure of flight number
if not number[:2].isaplha():
raise ValueError(f"No airline code in '{number}'")
if not number[:2].isupper():
raise ValueError(f"Invalid airline code '{number}'")
if not (number[2:].isdigit() and int(number[2:]) <= 9999):
raise ValueError(f"Invalid route number '{number}'")
self._number = number
def number(self):
return self._number or "SN060"
def airline_code(self):
return self._number[:2]
_number
?number()