Python 3-Classes and Objects

Class

Class is a blueprint for the object. Class is a container having attributes (variables) and behaviors (functions).

To create a class, use the keyword ‘class’:

class MyClass:
  x = 5
print(MyClass)

Output:

From class, we construct instances. In other words, an instance is a specific object created from a particular class.

 

Object

An object (instance) is an instantiation of a class. When class is defined, only the description for the object is defined. Hence, no memory or storage is allocated.

Example:

class Peacock:
pass
obj = Peacock()

For the above empty class Peacock, here ‘obj’ is the object of class.

 

__init__() Function:

The __init__() Function is a built-in function in python. All classes have a function called __init__(), which is always executed when the class is being initiated.

Example:

Create a class named Employee, use the __init__() Function to assign values for name and Designation:

class Employee:
    def __init__(self, name, designation):
        self.name = name
        self.designation = designation
        
e1 = Employee("John", "Software Engineer")

print("Name: "+e1.name)
print("Designation: "+e1.designation)

Output:

Name: John
Designation: Software Engineer

Object Methods:

Object can also contain methods. Methods in object are functions that belong to the object.

Let us create a method in a Employee class.

Example:

class Employee:
    def __init__(self, name, designation):
        self.name = name
        self.designation = designation
    
    def greeting(self):
        print("Hello! We welcome "+self.name)
        
e1 = Employee("John", "Software Engineer")
e1.greeting()

Output:

Hello! We welcome John

‘self’ parameter:

The self parameter is a reference to the current instance of the class and it is used to access variables that belong to the class. It does not to be named ‘self’, you can call it whatever you like, but it should be of first parameter of any function in the class.

Example:

class Employee:
    def __init__(abc, name, designation):
        abc.name = name
        abc.designation = designation
    
    def greeting(xyz):
        print("Hello! We welcome "+xyz.name)
        
e1 = Employee("John", "Software Engineer")
e1.greeting()

Output:

Hello! We welcome John

In the above example, ‘self’ parameter is not used, instead, we used ‘abc’ and ‘xyz’  but the result is as expected.

 

Modify object Properties:

The object properties can be modified as shown below:

Example:

Set the designation of employee as ‘Test Engineer’

e1.designation = ‘Test Engineer’

Delete object Properties:

The object properties can be deleted using the ‘del’ keyword as shown below:

Example:

del e1.designation

Delete objects:

The objects can be deleted also using the ‘del’ keyword as shown below:

Example:

del e1