Classes

Creating Classes

Create a class with:

class ClassName:
    ...

Instanciate it

Then create an object from this class with:

obj = ClassName()

__init__() function

All classes have a function __init__() which is basically the class constructor.

class MyClass:
    __init__(self, otherParams):
        self.something = otherParams

obj = MyClass('someValue')

__str__() function

Controls what should be returned when the class object is represented as a string.

If not set, the string representation of the object is returned.

Use it to format the way you wish when printed.

self parameter

Is a reference to the current instance of the class.

You do not have to name it self, you can call it whatever you want, it just HAVE to be the first parameter.

Inheritance

Allows us to define a class that inherits all the methods and properties from another class.

To do this you simply inform the Parent class name when creating the class:

class Student(Person):
    ...

Overwriting the parent constructor

To overwrite it you just declare a constructor for the child class.

class Student(Person):
    def __init__(self, ...):
        ...

Overwriting but also calling the parents constructor

class Student(Person):
    def __init__(self, ...):
        Person.__init__(self, ...)
        ...

You can also use super():

class Student(Person):
    def __init__(self, ...):
        # Note that you don't have to pass the 'self' as parameter to the 'super'
        super().__init__(...)

Polymorphism

All these class have a move() method, since they inherit from Vehicle, and some class overwrite and some don't.

Also check the use of pass in the Car class, since it does nothing but inherit.

class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def move(self):
        print("Move!")

class Car(Vehicle):
    pass

class Boat(Vehicle):
    def move(self):
        print("Sail!")

class Plane(Vehicle):
    def move(self):
        print("Fly!")

car1 = Car("Ford", "Mustang")        # Create a Car object
boat1 = Boat("Ibiza", "Touring 20")  # Create a Boat object
plane1 = Plane("Boeing", "747")      # Create a Plane object

for x in (car1, boat1, plane1):
    print(x.brand)
    print(x.model)
    x.move()

Last updated