Python Classes and Objects

  • Post category:python
  • Reading time:11 mins read

What is an Object ? 

Object is the most basic concept and a key to understand the Object-Oriented programming . Object is an entity that has two characteristics , State and Behavior . Some examples of real world object can be : Bike , Chair , Dog etc. Lets take an example of a Bike . Bike has some state ( current gear , current speed ) and behavior ( change gear , apply brake ) .

One way to begin thinking in an object-oriented way is to identify the state and behavior of real world objects . Software objects are also similar to the real world objects. They too contains State and Behavior . An Object stores its state in fields and exposes the behavior through methods.

What is Class ?

Class is a blueprint from which objects of same type can be created . Lets take an example of a Bike again . There are thousands of bikes with the same characteristics i.e having same make and model . They are created from the same prototype / blueprint called class.

Here’s a simple example in Python:

Example: Employee Class in python

# Define the class
class Employee:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

    def __str__(self):
        return f"Name= {self.name}, Age= {self.age}, City= {self.city}"


# Create instance of the class
emp1 = Employee("Shivaay", 6, "Haridwar")

# Print the instance name.
print(emp1.name)

# Print the instance age.
print(emp1.age)

# Print the instance city.
print(emp1.city)

# Print the instance
print(emp1)

# Output
Shivaay
6
Haridwar
Name= Shivaay, Age= 6, City= Haridwar

In the above example code:

  • The Employee class has an __init__ method that initializes the attributes name, age, and city when an instance of the class is created.
  • The __str__ method returns a string representation of the object.
  • An instance emp1 of the Employee class is created with different values.
  • When print(emp1) is called, Python implicitly calls the __str__ method to convert the object to string, and the string representation is printed to the console.

What if we don’t define __str__ method ?

If you don’t define the __str__ method in your class, Python will use the default implementation provided by the base object class. This default implementation returns a string that includes the class name and the memory address of the object in hexadecimal format.

Here’s how the class would behave without explicitly defining the __str__ method:

class Employee:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

# Create an instance of the class
emp = Employee("John", 30, "New York")

# Print the instance
print(emp)

# Output
<__main__.Employee object at 0x000001DFE0DED370>

In this case:

  • The Employee class does not define a custom __str__ method.
  • When you print the emp instance, Python uses the default __str__ method from the base object class, which returns a string containing the class name (Employee) and the memory address where the object is stored in hexadecimal format.

Defining a custom __str__ method allows you to provide a more informative and readable representation of your objects.

What is __init__ method in Python ?

__init__ is a special method in Python classes. It stands for “initialize” and is also known as the constructor method. When you create an instance of a class, the __init__ method is automatically called. Its primary purpose is to initialize the object’s attributes.

Here’s a basic explanation of how __init__ works:

  • When you create an object of a class, Python automatically calls the __init__ method of that class.
  • The __init__ method can take parameters, allowing you to pass initial values to the object’s attributes during creation.
  • Inside __init__, you typically set up the initial state of the object by assigning values to its attributes using the self keyword.
  • The self parameter represents the instance of the class and allows you to access the attributes and methods of the object within the class.
  • You can also perform other initialization tasks within __init__, such as opening files, establishing connections, or performing calculations.

The self Parameter in python class

In Python, self is a conventionally used parameter name in instance methods of a class. It represents the instance of the class (i.e., the object) itself. When you call a method on an object, Python automatically passes the object itself as the first parameter to the method. This parameter is traditionally named self, although you can technically name it anything you like, but sticking with self is a widely accepted convention and makes your code more readable for others familiar with Python.

Here’s how self works in Python classes:

  • When you define a method within a class, you must include self as the first parameter of the method definition.
  • When you call a method on an object, Python automatically passes the object itself as the self parameter to the method.
  • Inside the method, you can access the attributes and methods of the object using the self keyword.

Here’s a simple example to illustrate the usage of self:

class MyClass:
    def __init__(self, value):
        self.value = value  # 'self' refers to the instance being created
        # Here 'value' is an instance variable.

    def print_value(self):
        print(self.value)  # Accessing instance variable using 'self'

# Creating an instance of MyClass
obj = MyClass(10)

# Calling a method on the object
obj.print_value()  

# Output: 
10

In this example:

  • In the __init__ method, self refers to the instance of MyClass being created. self.value refers to the value attribute of that instance.
  • In the print_value method, self again refers to the instance of MyClass. self.value accesses the value attribute of that instance.
  • When calling the print_value method on the obj object, Python automatically passes obj as the self parameter to the method.

Modifying Object Properties

You can modify properties on objects like this:

class Employee:

    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

    def __str__(self):
        return f"Name= {self.name}, Age= {self.age}, City= {self.city}"


# Creating an Object of class Employee.
emp1 = Employee("Shivaay", 6, "Haridwar")
print(emp1.name)
emp1.name = "Shvaay Singh Chauhan"
print(emp1.name)

# Output
Shivaay
Shvaay Singh Chauhan

Deleting Object Properties

You can delete properties on objects by using the del keyword:

class Employee:

    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

    def __str__(self):
        return f"Name= {self.name}, Age= {self.age}, City= {self.city}"


# Creating an Object of class Employee.
emp1 = Employee("Shivaay", 6, "Haridwar")

print(emp1.age)

# Deleting object property.
del emp1.age
print(emp1.age)

# Output
AttributeError: 'Employee' object has no attribute 'age'

you can delete the emp1 object as below

del emp1
print(emp1)

# Output
NameError: name 'emp1' is not defined

The pass Statement

In functions, the pass statement serves as a placeholder when you define a function but don’t want to implement its functionality yet. It allows you to create a valid function structure without any code inside its body.

Here’s how you can use pass in a function:

def my_function():
    pass

my_function()

In this example:

  • We define a function called my_function.
  • Inside the function body, we use the pass statement, which means that the function does nothing when called.
  • When you call my_function(), it will execute without any errors, but it won’t perform any actions.

The pass statement is particularly useful in scenarios where you’re designing the structure of your program and need to define functions that will be implemented later. It helps in maintaining the syntactic correctness of your code without having to provide the implementation details immediately.