Object Oriented Programming In Python🚀 With Examples💡 - Part One

Introduction

 
In computer science, there are various programming languages available for instructing systems or computing devices. OOP is one of the fundamental concepts for every computer language to provide a clear modular structure and effective way of solving problems.
 

OOPs

 
Object-oriented programming (OOP) is a programming paradigm that deals with various fundamentals of its concepts. After the procedural language revolution, the OOPs concept has become an essential part of our programming world to achieve better productivity, flexibility, user-friendliness, and rapid code management. Python is the best OOPs supported programming language since its existence It can solve programming problems where computation is done by the object. In the series of articles, we will learn the essential concepts available in Python OOPs.
 
List of OOPs concepts
  1. Class
  2. Object
  3. Method
  4. Inheritance
  5. Polymorphism
  6. Encapsulation
  7. Data abstraction

Class and objects in Python

 
Consider a class in OOPS as a user-defined prototype or blueprint of program attributes, instance methods and its set of instructions. It performs a way of binding a collection of objects to itself to lead large programs in a more understandable and manageable way.
 

Defining a Class in Python

 
Before creating a Class, we should know a few essential instructions to build an effective class.
  • To create a class, use the “class” keyword followed by the class name.
  • The end of the Class name must declare a colon.
  • To declare a documentation string it is useful to get some more information about the class.
  • Using constructor in a class, we will be smoothly handling a large program. 
Syntax
 
Class classname:
   <Statement 1 >
    .
    .
    <Statement N >
 
Example
 
Create a class named fruits with their instances.
  1. class fruits:  #Class declaration
  2.     Name="Apple"  
  3.     No=A1  
  4.     def deisplay(self):  #Instance method
  5.         print(self.Name, self.No)            
Here, we declare a class named fruits which contains two fields as fruit Name and No.
 
Next, the method named “display()” will print the class instance attributes.
 

Creating a class instance

 
When we need to use the class attributes in another class or method, it is available by creating class instance attributes. 
 
Example 
  1. class employee:  
  2.     salutation="Wellcome All"   #class instance attribute  
  3.       
  4.     def __init__(self):    
  5.         self.Name = 'Kokila'      
  6.         self.Id = 101      
  7.     def display(self):          #class instance method  
  8.         print("Employee Name: %s \nId: %d" %(self.Name, self.Id))      
  9. Emp=employee()                    
  10. print(Emp.salutation)           #call instance attribute  
  11. Emp.display()                   #call instance method  
  • Above the code, we declared class instance attributes under the class named “employee” and followed by the constructor.
  • Next, we declared an instance method named as the display () and created an object named as Emp. Then the “Emb.display()” statement will call the instance method to prints statements itself.
Output
 
Object Oriented Programming In Python
 

Python Constructor

 
In program construction, every statement like data attributes, class members, methods, and other objects must be present within the class boundary. 
 
A constructor is a special type of method that helps to initialize a newly created object. Depending on __init__ method we can pass any number of the arguments while creating the class object.
 
There are two types of constructed available in Python programs in order to initialize instance members of the class. Given below,
  • Non-parameterized constructer 
  • Parameterized constructor
In python programming, A constructor can declare like "__init__ ()" method. The underscore indicates it is a special method then followed by the “init” is represents the acronym of initialization.
 
If the method generally wrapped itself in the initial declaration of class attributes, it automatically gets called when we create an object belong to the corresponding class.
 
Example
  1. class fruits:  #Class declaration
  2.     total=0  
  3.     def __init__(self,fno,fname,fcolor):  #Constructor declaration
  4.         self.fno=fno  
  5.         self.fname=fname  
  6.         self.fcolor=fcolor  

Non-parameterized constructor

 
Nonparameterized constructor, we cannot pass any arguments by its parameter.
 
It's also known as a simple default constructor and has only one argument that is a reference to the instance being constructed.
 
Example
  1. class Csharpcorner:  
  2.     community=""  
  3.     def __init__(self):  #constructor declared without any arguments
  4.         self.community="Wellcome to C# corner"  
  5.   
  6.     def display(self):  
  7.         print(self.community)  
  8. obj=Csharpcorner()       #Constructor automatically execute by the object creation
  9. obj.display()   
Here, we declared a class named Csharpcorner and the constructor. The constructor doesn't contain any passing arguments. When we execute the “obj=Csharpcorner” statement, the default constructor will execute.
 
Output
 
Object Oriented Programming In Python
 

Parameterized constructor

 
A constructor with arguments is known as the parameterized constructor used for setting up properties of the object. So, we can initialize an object with some values while declaring. In python, the first argument considers as a reference to the instance known as the “self” keyword.
 
Example
  1. class fruits:  
  2.     total=0  
  3.     def __init__(self,fno,fname,fcolor):  #Constructor declared with number of arguments
  4.         self.fno=fno  
  5.         self.fname=fname  
  6.         self.fcolor=fcolor  
  7.         fruits.total+=1  
  8.     def displaytotal(self):  
  9.         print("No:",self.fno,"Fruite Name:",self.fname,",Fruite color:",self.fcolor)  
  10.     def displayfruit(self):  
  11.         print("No:",self.fno,"Fruite Name:",self.fname,",Fruite color:",self.fcolor)  
  12. f1=fruits(1,"Apple","Red"
  13. f2=fruits(2,"lemon","Yellow")  
  14. f1.displaytotal()    
  15. f2.displayfruit()    
  16. print("Total Number of Fruites %d" % fruits.total)  
For the parameterized constructor example, we declared three arguments within the parameter named as fno, fname, and fcolor.
 
Output
 
Object Oriented Programming In Python
 

Object in Python

 
In a programming language, objects considered as a value or variable of the Class simulates a real-world entity to enhance their accessibility and understandability. It allows us to create an instance of the class using the class name, and it is able to access all the methods of the specified class like “__init__” method. In Python, everything consists of an Object to deal with itself.
 
Syntax
 
<object-name> = <class-name>(<arguments>)
 
For creating an object, we can use the class named calculation to achieve that.
 
Example
  1. class calculation:              #Class declaration  
  2.       
  3.     def __init__(self,a,b):  
  4.         self.a=a  
  5.         self.b=b  
  6.   
  7.     def Add(self):  
  8.         print(self.a+self.b)  
  9.     def Divide(self):  
  10.         print(self.a/self.b)  
  11. c1=calculation(10,20)           #Declare object c1  
  12. c2=calculation(100,50)          #Declare object c2  
  13. c1.Add()                        #Call our Instance method Add  
  14. c2.Divide()                     #Call our instance method Divide 
Here, we created two objects from the class “calculation” named as c1 and c2.
 
Output
 
Object Oriented Programming In Python
 

Accessing class Attributes 

 
The Class Attribute, known as a class instance, is performed outside of the instance methods and any other private boundary.
 
Example
  1. class dog:     
  2.     name='Dommy'  #Class attribute 1  
  3.     age='4'       #Class attribute 2  
  4.     count=0       #Class atrribute 3  
  5.           
  6.     def show(self):     
  7.         self.name    
  8.         self.age  
  9.         dog.count+=1  
  10. d1 = dog()  
  11. d1.show()  
  12. d1.show()  
  13. print("The Dog name is:",d1.name)   #Accessing class attribute name  
  14. print("The Dog Age is:",d1.age)     #Accessing class attributes age  
  15. print("Count:",d1.count)            #Accessing class attribute count
Output
 
Object Oriented Programming In Python
 

Accessing Instance Attributes

 
In Python, we can access the object variable using the dot (.) operator. For calling the instance method in a program, you should create an Object from the class that will provide accessibility of class members and attributes with the help of the dot operator.
 
The self represents the instance of the class. By using that, we will get superior access to our class methods and attributes. If it is also an optional keyword, we can declare whatever we need as an identifier.
 
Therefore I will declare myself a keyword instead of self-keyword. Given below:
 
Example 
  1. class community:    
  2.   def __init__(myself, name, year):  #Here I mentioned myself rather than self  
  3.     myself.name = name    
  4.     myself.year = year    
  5.     
  6.   def myfunc(myself):    
  7.     print("Hello World")           
  8.     
  9. p1 = community("C# corner",2019)    
  10. p1.myfunc()  
  11. print("Wellcome to ", p1.name, + p1.year) #Accessing object variable
Output
 
Object Oriented Programming In Python
 
Attribute Update, Add, and Delete operations
  • p1.article=3      #Add “article” attribute
  • p1.article=5      #Update “article” attribute
  • Del p1.article     #Delete “article” attribute
Accessing attributes (In build class function)
  • Getattr(obj, name, [,default]) – it allows us to access attribute of an object.
  • Setattr(obj, name)                 – this method used to set an attribute. If it created when it does not exist.
  • Hasattr(obj, name)                – to check the attribute Exist or Not
  • Deleteattr(obj, name)            – Delete an attribute
Example
  1. class dog:   
  2.     name='Dommy'  
  3.     age='4'  
  4.     def show(self):   
  5.         print (self.name)  
  6.         print (self.age)   
  7. d1 = dog()   
  8. # Use getattr instead of d1.name   
  9. print (getattr(d1,'name'))  
  10.     
  11. # returns true if object has attribute   
  12. print (hasattr(d1,'name'))   
  13.     
  14. # sets an  attribute    
  15. setattr(d1,'height',152)   
  16.     
  17. # returns the value of attribute name height   
  18. print (getattr(d1,'height'))  
  19.     
  20. # delete the attribute   
  21. delattr(dog,'age')   
Output
 
Object Oriented Programming In Python
 

Built-in class Attributes

 
Python built-in class attributes give us some information about the class.
 
Every class in python can retain below an attribute and access by using the dot operator. 
  1. __dict__ :To holding the class namespace
  2. __doc__: To give the class documentation string or None, if #ff0000
  3. __name__ :It gives the class name
  4. __module__ :Itprovide module name in which the class is defined
  5. __bases__ : To give the bases of the class
Example
  1. class collors:  
  2.     'This is a sample class called collors'  
  3.     collorCount=0  
  4.     def __int__(self,red,yellow):  
  5.         self.red = Apple  
  6.         self.yellow = lemon  
  7.         collocrCount+=1  
  8.     def displayCount(self):  
  9.         print("Tottal collorCount %d" %collors.collorCount)  
  10.     def displayfruit(self):  
  11.         print("Red:"self.red, "Yellow:",self.yellow)  
  12.   
  13. print("collors.__doc__:",collors.__doc__)  
  14. print("Collos.__name__:", collors.__name__)  
  15. print("collors.__module__:", collors.__module__)  
  16. print("collors.__bases__:", collors.__bases__)  
  17. print("collors.__dict__:", collors.__dict__) 
Output
 
Object Oriented Programming In Python
 

Python Method

 
A method is a function wrapped with a collection of statements handled inside the body of the class. It will do some specific tasks and return a result to the requester.
 
Benefits of methods
  • Code reusability
  • Wrapping and protecting the code
  • Determine code accessibility
Syntax
 
Def functionname (arguments):
 
“““Function docstring”””
 
   Statements
 
   Return[expression]
 
 
Example
  1. class Student:      
  2.     # Constructor special method      
  3.     def __init__(self, name):      
  4.         print("This is constructor")      
  5.         self.name = name  
  6.     # method  
  7.     def show(self):      
  8.         print("Hello",self.name)      
  9. student = Student("C# corner")  
  10. #calling the method  
  11. student.show()   
Output
 
Object Oriented Programming In Python
 
In the above program, we defined two types of instance methods named as sleep() and play().
 
Next, we define the object named "student" from our class named Dommy. When we call our instance method by the object, then the corresponding instance method will be executed and print.
 

Summary

 
I hope, you understood very well about Python OOPs techniques such as Class, Object, and method with simple examples. The remaining concepts, we will discuss in the next article. Stay tuned.


Similar Articles