Jump to content

Classes

From Slow Like Wiki

Basic Class


class Cat:                                          # Use capital letter for class name
    """Basic class with simple attributes 
    and methods """

    def __init__(self, name, age):                  # Special method to create an instance
        """Initialize attributes"""
        self.name = name
        self.age = age

    def eat(self):                                  # Method defined in class
        """Simulate cat eating"""
        print(f"{self.name} is eating.")

    def sleep(self):
        """Simulate cat sleeping"""
        print(f"{self.name} is sleeping.")

my_cat = Cat('Sushi', 4)                            # Create one instance
your_cat = Cat('Basil', 3)                          # Create another
print(f"My cat is called {my_cat.name} \
and your cat is called {your_cat.name}.") 
my_cat.eat()                                        # Call method
your_cat.sleep()

Parent Classes, Child Classes, and Compositions


class Car:                                          # Parent class defined first in module
    """Basic car class"""

    def __init__(self, make, model, year):
        """Initialize attributes"""
        self.make = make
        self.model = model
        self.year = year
        self.odo = 0

    def get_summary(self):
        """Return summary info"""
        summary = f"{self.year} {self.make} {self.model}"
        return summary.title()

    def read_odo(self):
        """ Show mileage """
        print(f"This car has driven {self.odo} miles.")

    def update_odo(self, mileage):
        """Set odo to new value"""
        if mileage >= self.odo:
            self.odo = mileage
            print(f"Odo updated to {self.odo}")
        else:
            print("You can't roll back the odo!")

my_car = Car('citroen', 'c4', 2012)
print(my_car.get_summary())
my_car.update_odo(123456)
my_car.read_odo()

class ElectricCar(Car):                                    # Child class calls parent class
    """Child Class for electric cars"""

    def __init__(self, make, model, year):
        """Initialize Attributes"""
        super().__init__(make, model, year)                # initialize parent class attributes
        self.battery = Battery()                           # initialize local attributes (call battery class)

class Battery:
    """Separate Class to model batteries"""

    def __init__(self, battery_capacity = 40):
        """Initialize Attributes"""
        self.battery_capacity = battery_capacity           # initialize local attributes

    def get_battery_capacity(self):
        """Print battery info"""
        print(f"This car is equipped with a {self.battery_capacity}-KWh battery.")

    def get_battery_range(self):
        """Print battery range"""
        if self.battery_capacity == 40:
            range = 150
        elif self.battery_capacity == 65:
            range = 225

        print(f"This car has a range of approximately {range}.")


your_car = ElectricCar('Tesla', 'model 3', 2024)
print(f"Your car is a {your_car.get_summary()}")
print(your_car.battery.get_battery_capacity())             # via the battery attribute
print(your_car.battery.get_battery_range())