Type Annotations in Python are optional metadata that specify the expected data type of variables, function parameters, and return values. While not enforced at runtime by Python itself, they are essential for code clarity and automated linting.
In the example VERSION: Final[str] = '1.0.12', the variable name is VERSION. The type annotation segment is : Final[str]. This informs the developer (and the IDE) that this variable is intended to be a constant string and should not be modified.
| Code Segment | Data Type | Functional Intent |
|---|---|---|
PI: Final[float] |
Float / Constant | Defines a constant numerical value with decimal precision. |
brand: str |
String | Expects text-based data for identification. |
horsepower: int |
Integer | Expects whole numbers for mathematical operations. |
turned_on: bool |
Boolean | Tracks binary state (True/False) for logic branching. |
The following labs demonstrate class construction, initialization (__init__), and the implementation of dunder methods like __str__ and __add__.
class Microwave:
def __init__(self, brand: str, power_rating: str) -> None:
self.brand = brand
self.power_rating = power_rating
self.turned_on: bool = False
def turn_on(self) -> None:
if self.turned_on:
print(f'Microwave ({self.brand}) is already turned on')
else:
self.turned_on = True
print(f'Microwave ({self.brand}) is now turned on')
def run(self, seconds: int) -> None:
if self.turned_on:
print(f'Running ({self.brand}) for {seconds} seconds')
else:
print(f"must power on first")
def __str__(self):
return f'{self.brand} (Rating: {self.power_rating})'
class Car:
def __init__(self, brand: str, horsepower: int) -> None:
self.brand = brand
self.horsepower = horsepower
def __str__(self) -> str:
return f'{self.brand}, {self.horsepower}hp'
def __add__(self, other) -> str:
return f'{self.brand} & {other.brand}'
volvo: Car = Car('Volvo', 200)
bmw: Car = Car('BMW', 240)
print(volvo) # Output: Volvo, 200hp
print(volvo + bmw) # Output: Volvo & BMW
This ledger recaps the specific Python 3.x logic and OOP structures verified during these lab sessions.
| Domain | Verified Action / Command | Functional Result |
|---|---|---|
| OOP | Class Instantiation | Successfully created unique objects from the Microwave and Car templates. |
| OOP | Dunder Method Implementation | Verified __add__ and __str__ functionality for custom object behavior. |
| Typing | Logic Audit: Type Annotations | Verified syntax for optional type hinting and the Final type alias. |
Also see: Java demo →