python template class code example
Example 1: python template generics
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
def empty(self) -> bool:
return not self.items
Example 2: python classes
class Box(object):
def __init__(self, color, width, height):
self.color = color
self.width = width
self.height = height
self.area = width * height
def writeAboutBox(self):
print(f"I'm a box with the area of {self.area}, and a color of: {self.color}!")
greenSquare = Box("green", 10, 10)
greenSquare.writeAboutBox()