CoachFullStack

Python Guide #14: Classes

One of programming paradigms available in Python is object oriented programming (OOP). In this paradigm, useful tool is a class, which is a code template for creating objects.

Imagine car as being an object. Car has its properties: horse power, tank capacity, max speed, fuel use per 100km. Car can also perform some tasks and some actions can be performed on the car. Car can drive, which uses fuel, you can tank your car, and so on.

Lets create car as an object with variables and methods in Python.

class car:
    # method init is called during object
    # creation
    def __init__(self, capacity, fuel_in_tank, fuel_usage):
        # "self" is how object refers to itself
        # if you plan to use self, then
        # you need to pass it as
        # first parameter in method
        # during initialization
        # we pass parameters, that
        # car will have at the beginning
        self.capacity = capacity
        self.fuel_in_tank = fuel_in_tank
        self.fuel_usage = fuel_usage
    
    def drive(self, distance):
        max_distance = self.fuel_in_tank * 100 / self.fuel_usage
        if distance >= max_distance:
            self.fuel_in_tank = 0
            print("You used up your whole fuel.", "You drove for:",
                max_distance, "km and need to tank."
            )
        else:
            self.fuel_in_tank = self.capacity - distance * 0.01 * self.fuel_usage
            print("You drove for", distance, "km, remaining fuel:", self.fuel_in_tank, "L")
        
    def tank(self, amount):
        self.fuel_in_tank += amount
        if self.fuel_in_tank > self.capacity:
            self.fuel_in_tank = self.capacity
            print("You can't tank so much, tanked", self.capacity - self.fuel_in_tank, "L")
        else:
            print("You tanked", amount, "L, remaining fuel:", self.fuel_in_tank)

my_car = car(100, 50, 8)
my_car.drive(300)
my_car.tank(5)

Execute program above. Feel free to modify different values, and see how it affects program behaviour. Study this example well.



Next: Modern Web Developement Is Awful

Previous: Python Guide #13: Object Methods