February 10, 2021

Python Classes and Objects

In this tutorial you will learn how to define a class in Python and how to create an object of a class in Python.

Class in Python

A class in any object oriented programming language provides a blueprint for a new type. A class encapsulates both data and functionality together which means a class in Python can contain variables and function definition that can manipulate those variables.

Syntax for creating class in Python

To create a class use keyword class followed by class name-

class ClassName(BaseClassName):
  '''doc string describing what the class is about'''
  class variables
  def __init__(self):
  def method1(self):
  def method2(self):

If class is extending any class then that class name is given in parenthesis. If class is not extending any other class then parenthesis are not required.

class ClassName:

A doc string written using triple double quotes or triple single quotes gives information about the class. It is optional.

Class variables are variables shared by all the instances of the class. Class variables should be defined outside the scope of any class method definitions.

__init__() is a special function that acts as a construcotr of the class. When an object of the class is created __init__() is invoked automatically to initialize the object.

method1(self), method2(self) are methods in the class.

First argument of a method is called self and it is a reference to the current instance of the class. This is nothing more than a convention, self is not a keyword in Python you can name it whatever you want but it is not advisable as by not following the convention your code may be less readable to other Python programmers.

Python class example

Here is a class Employee that specifies attributes emp_id, name and age and a method display_info() that prints the value of those attributes.

class Employee:
  def __init__(self, emp_id, name, department):
    self.emp_id = emp_id
    self.name = name
    self.department = department

  def display_info(self):
    print('Id:', self.emp_id)
    print('Name:', self.name)
    print('Department:', self.department)

Object in Python

Once you have a class definition you can create objects (instances) of that class. Class provides a blueprint; what attributes and methods should be there whereas object is an entity with actual values and a place in memory.

An object has state and behavior. Values given to the attributes give object its state and its behavior is specified by the methods that can modify its state.

Syntax for creating an object in Python-

obj = ClassName()

Python object creation example

We’ll take the same class as defined above and create two objects of that class.

class Employee:
  def __init__(self, emp_id, name, department):
    self.emp_id = emp_id
    self.name = name
    self.department = department

  def display_info(self):
    print('Id:', self.emp_id)
    print('Name:', self.name)
    print('Department:', self.department)


emp1 = Employee(1, 'Renee', 'HR')
emp2 = Employee(2, 'Jerry', 'IT')
emp1.display_info()
emp2.display_info()
Output
Id: 1
Name: Renee
Department: HR
Id: 2
Name: Jerry
Department: IT

Here objects are created in these statements

emp1 = Employee(1, 'Renee', 'HR') emp2 = Employee(2, 'Jerry', 'IT')

For each object __init__() function is called to initialize the object (set values for the attributes). Both of the objects are of type Employee but have their separate states which can be seen by invoking the display_info() method on each object.

Once you create an object of a class in Python, memory for that object is allocated on the heap. Reference to that memory is stored in variable, emp1 and emp2 in the example. Following image illustrates the memory allocation for the object and how that memory is referenced.

Python class and object

Class and instance variables

Instance variables are the variables unique to each instance of the class where as class variables are the variables shared by each instance. In the Employee class we’ll add a class variable to keep track of the number of objects created.

class Employee:
  no_of_objects_created = 0
    
  def __init__(self, emp_id, name, department):
    self.emp_id = emp_id
    self.name = name
    self.department = department
    # Accessing class variable
    Employee.no_of_objects_created += 1

  def display_info(self):
    print('Id:', self.emp_id)
    print('Name:', self.name)
    print('Department:', self.department)


emp1 = Employee(1, 'Renee', 'HR')
emp2 = Employee(2, 'Jerry', 'IT')
emp1.display_info()
emp2.display_info()
print('Total number of objects created- ', Employee.no_of_objects_created)
Output
Id: 1
Name: Renee
Department: HR
Id: 2
Name: Jerry
Department: IT
Total number of objects created-  2

That's all for the topic Python Classes and Objects. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment