Python

Python Classes

Python Classes

As a object-oriented programming language, Python supports the use of classes and objects. Most of the programming language of Python is objects. And objects can be anything.

Classes encompass functions, variables and data into one. They can be referred as the template for objects. In other words, with the creation of a class, a new type of object is created.

For instance, the whole concept of a car represents a class. Meaning, the class defines what a car is: it has wheels, engine, certain shape, number of doors, colour, and so on. The object will represent any specific car model, such as a BMW M4 or Mercedes-Benz C Class.

A class can include properties (features) and methods (functions). Properties define the objects and methods add functionality to said objects. Following the above example, properties are all the different parts of a car: engine, colour, number of doors, etc. And methods are accelerate, break, and so on.

The main keyword for creating a class is “class” and “def” for methods. Indentation and colons are essential.

# Class
class Car:
    a = "something"

# Object
car1 = Car()
car2 = Car()

The above is a very basic representation of creating a class and two objects.

Classes also have built-in functions, which are very important. A very common built-in function is “__init__“. This function assigns values to the properties.

# Class 
class Car:
    def __init__ (self, model, colour, n_doors):
        self.model = model
        self.colour = colour
        self.n_doors = n_doors

# Objects
car1 = Car("XYZ Ultimate", "Blue", 4)
car2 = Car("ABV Extreme", "Yellow", 2)

print(car1.model)
print(car2.n_doors)

# Output: XYZ Ultimate 
# Output: 2 

The “__init__” built-in function declares all properties. The “self” word refers to the current instance of the class, and it always goes first.

The name “self” is conventional and can be anything, but the recommendation is not to change it as it is very common.

python classes syntax programming coding tutorial

Next: Python Files

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.