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:

Overwriting the parent constructor

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

Overwriting but also calling the parents constructor

You can also use super():

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.

Last updated