Python Classes


Python Classes and objects

Python Classes

Python Class

Class is famously said to be the blueprint of the object. The term object comes from the fact that it resembles real-life objects. In the real world, everything is an object having some attributes and characteristics that make it unique.

For example, the chair you are sitting on is an object. There are different kinds of chairs with different shapes, sizes and color, etc., but all are chairs

The same is the case with Dogs, when we see a dog, we all say this is a dog. But every dog is not the same. They all have certain attributes like name, breed, color, etc. These attributes are known as the data members. They also have certain behaviors in common like, a dog can perform actions like eat, bark, sleep, etc. These behaviors are known as the methods.

Definition of class

The class is known as the blueprint of the object. It is a user-defined data structure that binds data members and methods (means it binds attributes and behaviors).

By data members, we mean the variables that objects of the class can access, and by member functions, we mean the methods that objects of the class can access.

Python Objects

We can say that an object is the instance of the class. It is a collection of data members and methods. Each instance of the class is independent of the class. Changing one instance of the object does not affect the other. For example, the color of one dog is independent of others.

Properties of objects:

IdentityIt gives a unique name to an object.
StateThe state of the object is represented by the attributes/properties of an object.
BehaviorThe behavior of the object is represented by the methods of an object.
Python Classes and objects

Creating a Class

Classes are made using the class keyword followed by the name of the class. In the below example, we have created the car class without anybody.

Syntax:

class <classname>:
    #body of class

Example:

In [1]:
class car:
    pass

Below is the example of the ‘car’ class with property as comapny_name and company_owner.

In [1]:
class car:
    company_name = "Tesla"
    company_owner = "Elon Musk"

Creating an Object

We have to follow the below syntax to create the object of the class.

Syntax:

<objectname> = <classname>(<parameters>)

Here in the below example we will create an object of class ‘car’ for their famous sedan model3. This object will be able to access all the class properties.

In the example, you can see that, we are accessing class properties using the <objectname>.<propertyname>.

Example:

In [1]:
class car:
    company_name = "Tesla"
    company_owner = "Elon Musk"

Creating the object of class.

In [2]:
model3 = car()

Accessing the object property.

In [3]:
print(car.company_name)
print(car.company_owner)
Tesla
Elon Musk

The __init__() Method

The __init__() method is the in-built method that is called whenever we create the object of the class. It is used to assign values to the data members, along with doing the other necessary tasks that need to be done during the creation of the object. In other words, it is used to initialize the object state while the object is created. In the __init__() method also, it is mandatory to use the first argument as the self keyword.

Example:

In [1]:
class car:
    company_name = "Tesla"
    company_owner = "Elon Musk"
    
    def __init__(self):
        print("Inside init.")

init method getting called for each object we created for class.

In [2]:
model_3 = car()
model_S = car()
Inside init.
Inside init.

Using init to assign values to object properties “car_type” and “seating_capacity”.

In [3]:
class car:
    company_name = "Tesla"
    company_owner = "Elon Musk"
    
    def __init__(self, car_type, seating_capacity):
        self.car_type = car_type
        self.seating_capacity = seating_capacity

Creating object of class.

In [4]:
model_3 = car("Sedan",5)

Accessing the object property “car_type”.

In [5]:
print(model_3.car_type)
Sedan

The self Parameter

The self parameter is the mandatory parameter to be passed to every method in the class. It acts as the reference to the instance of the class. It is used to access the instance variables. Furthermore, it is always supposed to be the first parameter of the class method.

Though at most of the places we can see that we use ‘self’ keyword, but self is not a keyword, we can use any name instead of self, it can be your’s name too, but yes, we always prefer to use some meaningful name.

Example:

Using self to initialize instance variables.

In [1]:
class car:
    company_name = "Tesla"
    company_owner = "Elon Musk"
    
    def __init__(self, car_type, seating_capacity):
        self.car_type = car_type
        self.seating_capacity = seating_capacity
In [2]:
model_3 = car("Sedan",5)
print(model_3.car_type)
Sedan

Using name “Bill” instead of self.

In [3]:
class car:
    company_name = "Tesla"
    company_owner = "Elon Musk"
    
    def __init__(Bill, car_type, seating_capacity):
        Bill.car_type = car_type
        Bill.seating_capacity = seating_capacity
In [4]:
model_3 = car("Sedan",5)
print(model_3.car_type)
Sedan

The __str__() Method

Python has the __str__() method that is useful for debugging, creating logs, and showing object information. It is the string representation of the class objects, which will give the object the user-defined string representation which is easy for us to read and get the overview of the class object.

In [1]:
class car:
    def __init__(self, name, company):
        self.name = name
        self.company = company
        
    def __str__(self):
        return f"Name of car = {self.name} and company = {self.company}"
    
fortuner = car("Legender", "Toyota")

print(fortuner)
Name of car = Legender and company = Toyota

The pass keyword

We can use the pass statement to define the empty class. The class definition cannot be empty, in case it is empty, python will through an error. With the pass statement, we can define the class with the empty body.

In [1]:
class car:
    pass

Class Methods – Behavior of class

A class method is the function defined inside the class. This function represents the behavior of the class.

In [1]:
class size:
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth
        
    def area(self):
        print("Area =", self.length * self.breadth)
        
living_room1 = size(15,12)
living_room2 = size(16,12)

living_room1.area()
living_room2.area()
Area = 180
Area = 192

References

  1. Classes and Objects in Python
  2. Accessing Object Functions