Skip to content

Instantly share code, notes, and snippets.

@specialorange
Created November 10, 2025 00:53
Show Gist options
  • Select an option

  • Save specialorange/635a7e0a107d01904832e0bb11475063 to your computer and use it in GitHub Desktop.

Select an option

Save specialorange/635a7e0a107d01904832e0bb11475063 to your computer and use it in GitHub Desktop.
# 1. Defining Methods in a Class
class Tire:
"""A tire that a mechanic works with"""
def __init__(self, brand, size, pressure_psi):
"""Initialize a new tire"""
self.brand = brand
self.size = size # e.g., "225/65R17"
self.pressure_psi = pressure_psi
self.tread_depth_32nds = 10 # New tire has 10/32" tread
def inflate(self, target_psi):
"""Add air to reach target pressure"""
if target_psi > self.pressure_psi:
self.pressure_psi = target_psi
return f"Inflated to {self.pressure_psi} PSI"
else:
return f"Already at {self.pressure_psi} PSI"
def check_pressure(self):
"""Check if tire pressure is in safe range (32-35 PSI)"""
if self.pressure_psi < 32:
return "⚠️ LOW - Add air!"
elif self.pressure_psi > 35:
return "⚠️ HIGH - Release some air!"
else:
return "✓ Pressure is good"
def measure_tread(self):
"""Check if tread depth is safe (minimum 4/32")"""
if self.tread_depth_32nds < 4:
return f"⚠️ REPLACE - Only {self.tread_depth_32nds}/32\" left"
else:
return f"✓ Tread is {self.tread_depth_32nds}/32\" - good"
# Using the Tire class
my_tire = Tire("Michelin", "225/65R17", 28)
print(my_tire.check_pressure()) # ⚠️ LOW - Add air!
print(my_tire.inflate(33)) # Inflated to 33 PSI
print(my_tire.check_pressure()) # ✓ Pressure is good
# 2. Creating Class Attributes
class TireShop:
"""A tire shop with shared information for all instances"""
# CLASS ATTRIBUTES - shared by ALL tire shops of this chain
chain_name = "QuickTire Auto Service"
warranty_years = 3
labor_rate_per_hour = 125.00
shop_count = 0 # Track how many shops exist
def __init__(self, location, manager):
"""Initialize a specific shop location"""
# INSTANCE ATTRIBUTES - unique to each shop
self.location = location
self.manager = manager
self.tires_sold_today = 0
# Increment the total shop count
TireShop.shop_count += 1
def sell_tire_set(self, quantity=4):
"""Record tire sales"""
self.tires_sold_today += quantity
return f"Sold {quantity} tires at {self.location}"
def print_shop_info(self):
"""Display shop information"""
print(f"--- {TireShop.chain_name} ---")
print(f"Location: {self.location}")
print(f"Manager: {self.manager}")
print(f"Labor Rate: ${TireShop.labor_rate_per_hour}/hr")
print(f"Warranty: {TireShop.warranty_years} years")
print(f"Tires sold today: {self.tires_sold_today}")
# Create two shop locations
shop1 = TireShop("Downtown", "Mike")
shop2 = TireShop("Airport Road", "Sarah")
shop1.sell_tire_set(4)
shop2.sell_tire_set(8) # Sold two sets
shop1.print_shop_info()
shop2.print_shop_info()
print(f"\nTotal shops in chain: {TireShop.shop_count}")
# If the chain changes warranty, ALL shops get it
TireShop.warranty_years = 5
shop1.print_shop_info() # Now shows 5 years
# 3. Creating Class Methods
class Tire:
"""Tire with factory methods for common tire types"""
# Standard tire sizes and specs
tire_catalog = {
'sedan': {'size': '205/55R16', 'max_psi': 35, 'price': 120},
'suv': {'size': '265/70R17', 'max_psi': 40, 'price': 180},
'truck': {'size': '275/65R18', 'max_psi': 50, 'price': 220},
}
def __init__(self, size, max_psi, price, brand='Generic'):
self.size = size
self.max_psi = max_psi
self.price = price
self.brand = brand
@classmethod
def from_vehicle_type(cls, vehicle_type, brand='Generic'):
"""
CLASS METHOD - creates a Tire based on vehicle type
Uses 'cls' instead of 'self' because it works with the class itself
"""
if vehicle_type not in cls.tire_catalog:
raise ValueError(f"Unknown vehicle type: {vehicle_type}")
specs = cls.tire_catalog[vehicle_type]
return cls(
size=specs['size'],
max_psi=specs['max_psi'],
price=specs['price'],
brand=brand
)
@classmethod
def add_to_catalog(cls, vehicle_type, size, max_psi, price):
"""CLASS METHOD - add a new tire type to the catalog"""
cls.tire_catalog[vehicle_type] = {
'size': size,
'max_psi': max_psi,
'price': price
}
return f"Added {vehicle_type} tire to catalog"
def __str__(self):
return f"{self.brand} {self.size} - ${self.price} (max {self.max_psi} PSI)"
# Using class methods - easy tire creation!
sedan_tire = Tire.from_vehicle_type('sedan', brand='Michelin')
truck_tire = Tire.from_vehicle_type('truck', brand='Goodyear')
print(sedan_tire) # Michelin 205/55R16 - $120 (max 35 PSI)
print(truck_tire) # Goodyear 275/65R18 - $220 (max 50 PSI)
# Add a new tire type to the catalog
Tire.add_to_catalog('sports_car', '245/40R18', 42, 250)
sports_tire = Tire.from_vehicle_type('sports_car', brand='Pirelli')
print(sports_tire) # Pirelli 245/40R18 - $250 (max 42 PSI)
# 4. Overriding Methods
class Tire:
"""Base tire class"""
def __init__(self, brand, size, price):
self.brand = brand
self.size = size
self.price = price
self.is_mounted = False
def mount_on_vehicle(self):
"""Standard mounting procedure"""
self.is_mounted = True
return [
"1. Break bead from rim",
"2. Remove old tire",
"3. Mount new tire on rim",
"4. Inflate to spec",
"5. Balance tire"
]
def get_install_time(self):
"""Time to install (in minutes)"""
return 20 # Standard tire takes 20 min
class RunFlatTire(Tire):
"""Run-flat tire with special mounting procedure"""
def __init__(self, brand, size, price):
super().__init__(brand, size, price)
self.reinforced_sidewalls = True
# OVERRIDE the mounting method - run-flats need special care!
def mount_on_vehicle(self):
"""Run-flat tires need special tools and procedure"""
self.is_mounted = True
return [
"⚠️ Use RUN-FLAT MOUNTING EQUIPMENT!",
"1. Apply extra lubricant",
"2. Break bead carefully (reinforced)",
"3. Use run-flat mounting tools",
"4. Mount tire - watch for sidewall damage",
"5. Inflate slowly to 35 PSI",
"6. Balance with precision weights"
]
# OVERRIDE the install time - run-flats take longer!
def get_install_time(self):
"""Run-flats take 50% longer"""
return 30 # Takes 30 minutes instead of 20
class OffroadTire(Tire):
"""Offroad/mud tire with aggressive tread"""
def __init__(self, brand, size, price, tread_pattern):
super().__init__(brand, size, price)
self.tread_pattern = tread_pattern # "mud", "all-terrain", etc.
# OVERRIDE mount method for offroad tires
def mount_on_vehicle(self):
"""Offroad tires are heavier and need special balancing"""
self.is_mounted = True
return [
"1. Break bead (tire may be heavy!)",
"2. Remove old tire",
"3. Mount new offroad tire",
"4. Inflate to lower PSI (better traction)",
"5. Dynamic balance required for aggressive tread"
]
def get_install_time(self):
"""Offroad tires take longer due to weight and balancing"""
return 25
# Compare different tire types
def install_tire(tire):
"""Helper function to install any tire type"""
print(f"\n=== Installing {tire.brand} {tire.size} ===")
print(f"Type: {tire.__class__.__name__}")
print(f"Time estimate: {tire.get_install_time()} minutes")
print("\nSteps:")
for step in tire.mount_on_vehicle():
print(f" {step}")
# Each tire type uses its own overridden methods!
regular = Tire("Michelin", "205/55R16", 120)
runflat = RunFlatTire("Bridgestone", "225/45R17", 280)
offroad = OffroadTire("BFGoodrich", "285/75R16", 300, "all-terrain")
install_tire(regular) # Standard 20-min procedure
install_tire(runflat) # Special 30-min run-flat procedure
install_tire(offroad) # Heavy-duty 25-min offroad procedure
# 5. Implementing Multiple Inheritance
class Tire:
"""Base tire class"""
def __init__(self, brand, size, price):
self.brand = brand
self.size = size
self.price = price
def get_description(self):
return f"{self.brand} {self.size}"
class WinterCapable:
"""Mixin for winter-rated tires"""
def __init__(self):
self.snowflake_rated = True
self.min_temp_fahrenheit = -40
def is_safe_for_winter(self, temp_f):
"""Check if tire is safe at given temperature"""
if temp_f < self.min_temp_fahrenheit:
return f"❄️ Too cold! Rated for {self.min_temp_fahrenheit}°F and above"
return f"✓ Safe for {temp_f}°F"
def winter_features(self):
return "Deep sipes for snow traction"
class HighSpeedRated:
"""Mixin for high-performance speed ratings"""
def __init__(self):
self.speed_rating = 'H' # Up to 130 mph
self.max_speed_mph = 130
def check_speed_safe(self, speed_mph):
"""Check if speed is within tire rating"""
if speed_mph > self.max_speed_mph:
return f"⚠️ UNSAFE! Max speed is {self.max_speed_mph} mph"
return f"✓ Safe at {speed_mph} mph"
def performance_features(self):
return "Reinforced construction for high-speed stability"
class RunFlatCapable:
"""Mixin for run-flat technology"""
def __init__(self):
self.reinforced_sidewalls = True
self.flat_driving_miles = 50 # Can drive 50 miles when flat
def puncture_behavior(self):
return f"Can drive {self.flat_driving_miles} miles at 50 mph when flat"
def runflat_features(self):
return "Reinforced sidewalls maintain shape when deflated"
# MULTIPLE INHERITANCE - combine features!
class PerformanceWinterTire(Tire, WinterCapable, HighSpeedRated):
"""
Winter tire that can also handle high speeds
Inherits from: Tire, WinterCapable, HighSpeedRated
"""
def __init__(self, brand, size, price):
Tire.__init__(self, brand, size, price)
WinterCapable.__init__(self)
HighSpeedRated.__init__(self)
self.speed_rating = 'V' # Upgrade to 149 mph for performance
self.max_speed_mph = 149
def get_description(self):
"""Override to add all features"""
base = super().get_description()
return f"{base} (Winter Performance - {self.speed_rating} rated)"
class AllSeasonRunFlat(Tire, RunFlatCapable, HighSpeedRated):
"""
All-season tire with run-flat and speed rating
Inherits from: Tire, RunFlatCapable, HighSpeedRated
"""
def __init__(self, brand, size, price):
Tire.__init__(self, brand, size, price)
RunFlatCapable.__init__(self)
HighSpeedRated.__init__(self)
def get_description(self):
"""Override to add features"""
base = super().get_description()
return f"{base} (Run-Flat, {self.speed_rating} rated)"
class UltimateWinterTire(Tire, WinterCapable, RunFlatCapable, HighSpeedRated):
"""
Premium tire with EVERYTHING - winter, run-flat, and speed rating!
Inherits from: Tire, WinterCapable, RunFlatCapable, HighSpeedRated
"""
def __init__(self, brand, size, price):
Tire.__init__(self, brand, size, price)
WinterCapable.__init__(self)
RunFlatCapable.__init__(self)
HighSpeedRated.__init__(self)
def get_description(self):
"""Override to show premium features"""
base = super().get_description()
return f"{base} (PREMIUM: Winter + Run-Flat + {self.speed_rating} rated)"
# Test the different tire combinations
print("=== PERFORMANCE WINTER TIRE ===")
winter_perf = PerformanceWinterTire("Michelin", "225/45R17", 280)
print(winter_perf.get_description())
print(winter_perf.is_safe_for_winter(-20))
print(winter_perf.check_speed_safe(140))
print(f"Features: {winter_perf.winter_features()}")
print("\n=== ALL-SEASON RUN-FLAT ===")
runflat = AllSeasonRunFlat("Bridgestone", "245/40R18", 320)
print(runflat.get_description())
print(runflat.puncture_behavior())
print(runflat.check_speed_safe(120))
print(f"Features: {runflat.runflat_features()}")
print("\n=== ULTIMATE WINTER TIRE (Everything!) ===")
ultimate = UltimateWinterTire("Continental", "255/35R19", 450)
print(ultimate.get_description())
print(ultimate.is_safe_for_winter(-30))
print(ultimate.check_speed_safe(125))
print(ultimate.puncture_behavior())
print(f"Winter: {ultimate.winter_features()}")
print(f"Performance: {ultimate.performance_features()}")
print(f"Run-Flat: {ultimate.runflat_features()}")
# Summary for the Tire Mechanic
# 1. Instance Methods - Regular methods that work on individual tires (like inflate(), check_pressure())
# 2. Class Attributes - Shared data for all shops in a chain (like warranty_years, labor_rate)
# 3. Class Methods - Special methods that create objects in convenient ways (like from_vehicle_type())
# 4. Method Overriding - Child classes customize behavior (run-flat tires need different mounting steps)
# 5. Multiple Inheritance - Combine features from multiple classes (winter + run-flat + high-speed in one tire!)
# Each concept builds on the previous one, just like how you learn more advanced tire repair techniques after mastering the basics!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment