Today, we will discuss what are classes and why they are beneficial.
A class is a piece of code that defines what an object is. For example, an int comes from a class named int and a list object comes from a class named list. Note that an objects are distinguishable, that is, they can be given a custom name (variable name), while classes are indistinguishable, that is, they have one fixed name used for defining all of its objects.
To create a class, we use the class keyword. Inside a class, we specify an init method that sets up an object being defined using this class. The init method can use other classes as well, including user defined and predefined ones. For this article, we can use the example of a car:
Note the double underscores on the left and right of the word init.
Whenever we define a class, the init function should have the keyword self as an 'argument.' A value is not required to be passed as self, it is for accessing the properties of that class object. Another way to say it is that 'self' will be replaced with the name. In the above example, if we want to access the mileage property of an object called car_object, self.mileage would be car_object.mileage.
Let us now create an object using this class and print it:
You may notice that (in the above example) it printed <__main__.Car object at 0x0000022E18EF1C30> instead of what we may naturally expect (the details of the car). But, by default, user defined classes only print out what the variable type is and where it is in memory (not to be confused with storage). To make it print out the details, we can override the 'str' function in the class and make it print the car details instead of the raw data:
Note that we have to use return because methods are always required to return a value (Except for the __init__ method and methods that do not return any output). Here is an example of creating a method in the class that increments the mileage by a specified amount:
That is how you make and use classes in Python.