Special Offer - Enroll Now and Get 2 Course at ₹25000/- Only Explore Now!

All Courses
Python Classes and Objects

Python Classes and Objects

May 17th, 2019

Python Classes and Objects

Python is a high-level objected oriented programming language meaning that most of the code in Python is implemented using classes. Classes are used to group related things together. By definition, a class is a template or blueprint for creating objects. It defines the methods and variables that are common to all objects of the same class.
Whereas, objects are an instance of a class. It is an entity that has its own distinct characteristics and behavior. One template can be used to create an end number of objects.
To get a better understanding of this concept, let’s take the example of a car. There are different types of cars which can be differentiated by distinct the attributes they have such as brand, model, color, etc. We can consider each type of cars as objects where Car is its class as it provides the template to create these specific objects. The following example demonstrates a simple use of class Car to create objects. Here car1 is an object of Car. In general, multiple objects can be created using a class template.

Example

class Car: #class definition where Car is a class
def __init__(self, brand, model, color): #initializing a class
#Here, brand, model and color are general attributes of the class Car
self.brand = brand
self.model = model
self.color = color
car1 = Car("Ford", "Mustang", "Red") #car1 is an object with specific attributes
print(car1.brand) #accessing particular attribute(brand) of a specific object(car1)
print(car1.model) #accessing particular attribute(model) of a specific objectprint(car1.color) #accessing particular attribute(color) of a specific object

Output

Ford
Mustang
Red

python features

A python is an object-oriented programming language it has the following features

Inheritance

the derived class will inherit the properties of the base class or parent class. Inheritance is used to define a class which can inherit all the properties and methods of another class. A Parent class, also known as a base class or superclass, is where these properties and methods are inherited from. Whereas, child class, also called derived class or subclass, is the class that inherits from the parent class. A child class can also have additional attributes along with the inherited attributes. However, the parent class does not have access to the attributes of the child class.  Any class can be a parent class so the syntax would be the same as you would create any other class.
In order to create a child class which inherits from the parent class, the parameter for the child class needs to have the name of the parent class.  In the example below, a child class called Dog has been declared and inherits from the parent class Animal.

Example

class Person: #parent class
name = ""
def __init__(self, person_name):
self.name = person_name
def print_person_info(self):
print("Name:", self.name)
class Employee(Person):  v
employee_id = 0 #initializing new child class attribute
def __init__(self, employee_name, employee_id): #initializing new child instance attribute
Person.__init__(self, employee_name)
self.employee_id = employee_id
def print_employee_info(self):
print("Employee Name ", self.name)
print("ID ", self.employee_id)
p1 = Person("Ellen")
p1.print_person_info()
e1 = Employee("Grace", 13401)
e1.print_person_info()
e1.print_employee_info()

Polymorphism

  • Based on type of objects their functionality will differ.
  • Same function or method but based on type of objects their  functionality will differ.
  • It is achieved using function overloading and operator overloading.

Abstraction

Data hiding (Hiding of data )

Encapsulation

Wraping up of data and method (method will work on data )

Class

Class is one of the most important key feature in python. It is the collection of variables and methods. In which methods are working on variables to perform   targeted task.It act as template for creating object.

Creating a Class in Python

A class is declared by using the keyword “class” followed by the class name which follows the UpperLowerCase convention. The class header ends with a colon in Python. All the methods and variables of the class are defined within the body of the class and are indented.

class ClassName :class body/suite

sample classes:

class Employee(object):
def  __init__(name, emp_no, salary, bonus):
self.name=name
self.emp_no=emp_no
self.salary=salary
self.bonus=bonus
def get_net_salary(self):
return self.salary + self.bonus
def display_employee_detail(self):
print(“Employee Name: {}”.format(self.name))
print(“Employe No: {}”.format(self.emp_no))
print(“Salary: {}”.format(self.salary)) 
Above one is the example for class. Name must follow keyword class. Class Employee consists of four variables called name , emp_no, salaray, bonus. These varialbes are called instance variables. Also, It having two methods named get_net_salary() and display_employee details(). These methods are called instance methods.

Objects:

In order to access variables and methods in class, need to create object for that class. Object is the instance of the class.
Creating object for the class Employee as follow.

emp = Employee(‘Rajan’, ‘EM0001,’25000’,’1000’)
Here, emp is the object for the class Employee. When instantiating object for the class , it is mandatory to pass values to all variable used in __init__(). It is the special method in python for initialing instance variable for that object. Each object will hold separate copy of the variables used in the class. So it is called instance variables and methods working on these instance variable is called instance method.
While creating object , it will call special method __init__() and initializing instance variables with passed values. As created object, it could able to access variable and methods in class.
Suppose we want to know net salary of employee, Need to call method get_net_salary() method using object as follow. It will return net salary of the employee by adding salary and bonus
net_salaray = emp. get_net_salary()
In the same way, want to display details of the employee, need to call method display_employee_detail() as follow. It will display of the details of employee
emp.display_employee_detail()
Note that, methods are not doing anything interdependently. It just perform some task using variables. Not only method, instance variables are also accessible using object as follow.
print(emp.name)
Print(emp.emp_no)
Suppose want to alter any of the instance variable after creating object. It can be done as follow.
emp.name = ‘Ram’
In order to ensure the change in the variable name , just calling the method display_employee_details(). Now, it will display Ram as name instead of Rajan. In the same way , any of the instance variables can be altered with the help of the object.
It is possible to create any number of objects for single class as follow.
emp1 = Employee(‘Jothi’, ‘EM0002’,’65000’,’8000’)
emp2 = Employee(‘Mukesh’, ‘EM0003’,’44000’,’3000’)
emp3 = Employee(‘Rajan’, ‘EM004’,’35000’,’7000’)
It should be careful, while modifying instance variable using specific object in multiple object environment. Because, value may be assigned to instance variable of different object. It will lead to data collision.

Python Constructor

A constructor is called automatically when an instance or object is created. The __init__ function or method is also known as a constructor or initializer. Many classes often begin by defining a constructor in order to initialize the attributes of a class. It is a reserved method in Python classes. It would be the first definition of a class and looks as shown below.

Example

class Car:
def __init__(self, brand, model, color) #constructor
self.brand = brand
self.model = model
self.color = color

Self parameter

The self parameter is used to refer to the current instance of a class and is used for accessing the variables of the class in which it belongs to. It has to be placed in the first parameter of a function.

Example

class Flower:
def __init__(self, fname):
self.fname = fname
def intro_flower(self):
print("This flower is called", self.fname)
flower1 = Flower("Orchids")
flower1.intro_flower()

Attributes in Python

Attributes define the characteristics of a class. They are like variables that hold data. For instance, a class named Student can contain general characteristics or attributes of a student such as a name, grade, gender. The attributes can hold a specific value when creating an instance. For instance, name = “Peter”. The attribute of a class can be accessed by creating an object and using the dot operator followed by the attribute name. In order to access the attribute inside a class, the class needs to be instantiated first. This can be done by assigning the class to a variable. In this case, student1 is the object variable. This is known as object instantiation and is a way to call a constructor.

Example

class Student:
name = "Peter" #attribute
student1 = Student() #object instantiation by calling constructor
print(student1.name)

Output

Peter

Class attribute vs Instance attribute

A class attribute is similar to a global variable in which the attribute belongs to the class rather than a specific object. It is shared between all the objects in a class and is defined outside the constructor. In the example below, “school” is a class attribute which can be directly accessed by using the class name dot attribute.
On the other hand, an instance attribute is defined within a class function and cannot be shared among other objects. They are unique for each object.

Example

class Student:
school = "St.Xavier" #class attribute
def __init__(self, fname, school):
self.fname = fname # attribute
self.school = school
s1 = Student("Alice", Student.school) #school attribute can be directly accessed using class name
print("Name: ", s1.fname)
print("School: ", s1.school)

Output:

Name:  Alice                                                     
School:  St.Xavier

Methods in Python

A class wouldn’t be of much use without having any functionality. Functionalities can be implemented by adding attributes and functions that are related to the attributes. These functions in a class context are known as methods. Methods define the behaviour of an object. The following example has a method named update_name which allows the name of the student to be changed or updated.

Example

class Student:
name = "Peter"
def update_name(self, new_name):
self.name = new_name
student1 = Student() #object instantiation
print("Current name:", student1.name) #current name
student1.update_name("Pierre") #change current name to Pierre
print("New name: ", student1.name) #updated name is printed
Multiple methods can be created and used in Python which of each performs a specific task just like functions. It helps in the reuse of code by simply calling the method name and any methods can be accessed by an object once its defined. In the example below, there are two methods that have been defined: update_age is a simple method that allows the age of the student to be updated while update_grade method allows the grade of the student to be updated. Any number of instances of this particular class can use or access these methods. The methods would perform the same task but the values of each object can be unique.

Example

class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def update_age(self, new_age): #method specified to update current age
self.age = new_age
def update_grade(self, new_grade): #method specified to update current grade
self.grade = new_grade
student1 = Student("Derek", 15, 10) #object instantiation
print("Name:", student1.name) #name
print("Age:", student1.age) #age
print("Grade:", student1.grade) #grade
student1.update_age(16) #updated age
student1.update_grade(11) #change current name to Pierre
print("Update age:", student1.age) #current name
print("Update grade: ", student1.grade) #updated name is printed

Output:

Name: Derek
Age: 15
Grade: 10                                                                               
Update age: 16                                                                          
Update grade:  11                                                                        
Student profile:{'grade': 11, 'age': 16, 'name': 'Derek'} 

Creating multiple objects in Python

Infinite number of objects can also be created from the blueprint of its class. By referring to the object name, the value of the attributes of the particular object can be added or modified. Moreover, the unique values of each object can be accessed by calling the specific object name followed by a dot and then the attribute name.

Example

class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade    
student1 = Student("Derek", 15, 10)#object instantiation
print("Name:", student1.name)#name
print("Age:", student1.age)#age
print("Grade:", student1.grade)#grade
student2 = Student("Hayley", 14, 9)
print("\nName:", student2.name)
print("Age:", student2.age)
print("Grade:", student2.grade)       
student3 = Student("Carol", 14, 10)
print("\nName:", student3.name)
print("Age:", student3.age) print("Grade:", student3.grade)

Output:

Name: Derek
Age: 15                                                                                 
Grade: 10  
Name: Hayley                                                                             
Age: 14                                                                                 
Grade: 9  
Name: Carol                                                                             
Age: 14                                                                                 
Grade: 10

How to find out attributes of an object in Python

In order to find out all the attributes that describe an object in a particular class, the ,__dict__ attribute can be used. In this case, the class instance has attributes – name, age and grade. Upon calling the object name followed by a dot and then  the .__dict__ attribute, all the attributes with its specific values of the particular object is shown.

class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
student1 = Student("Derek", 15, 10) #object instantiation
print("Student profile: ", student1.__dict__) #show all attributes of current object