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
- Class
- Object
- Method
- Inheritance
- Polymorphism
- Encapsulation
- 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.
- class fruits: #Class declaration
- Name="Apple"
- No=A1
- def deisplay(self): #Instance method
- 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
- class employee:
- salutation="Wellcome All"
-
- def __init__(self):
- self.Name = 'Kokila'
- self.Id = 101
- def display(self):
- print("Employee Name: %s \nId: %d" %(self.Name, self.Id))
- Emp=employee()
- print(Emp.salutation)
- Emp.display()
- 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
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
- class fruits: #Class declaration
- total=0
- def __init__(self,fno,fname,fcolor): #Constructor declaration
- self.fno=fno
- self.fname=fname
- 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
- class Csharpcorner:
- community=""
- def __init__(self): #constructor declared without any arguments
- self.community="Wellcome to C# corner"
-
- def display(self):
- print(self.community)
- obj=Csharpcorner() #Constructor automatically execute by the object creation
- 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
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
- class fruits:
- total=0
- def __init__(self,fno,fname,fcolor): #Constructor declared with number of arguments
- self.fno=fno
- self.fname=fname
- self.fcolor=fcolor
- fruits.total+=1
- def displaytotal(self):
- print("No:",self.fno,"Fruite Name:",self.fname,",Fruite color:",self.fcolor)
- def displayfruit(self):
- print("No:",self.fno,"Fruite Name:",self.fname,",Fruite color:",self.fcolor)
- f1=fruits(1,"Apple","Red")
- f2=fruits(2,"lemon","Yellow")
- f1.displaytotal()
- f2.displayfruit()
- 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
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
- class calculation:
-
- def __init__(self,a,b):
- self.a=a
- self.b=b
-
- def Add(self):
- print(self.a+self.b)
- def Divide(self):
- print(self.a/self.b)
- c1=calculation(10,20)
- c2=calculation(100,50)
- c1.Add()
- c2.Divide()
Here, we created two objects from the class “calculation” named as c1 and c2.
Output
Accessing class Attributes
The Class Attribute, known as a class instance, is performed outside of the instance methods and any other private boundary.
Example
- class dog:
- name='Dommy'
- age='4'
- count=0
-
- def show(self):
- self.name
- self.age
- dog.count+=1
- d1 = dog()
- d1.show()
- d1.show()
- print("The Dog name is:",d1.name)
- print("The Dog Age is:",d1.age)
- print("Count:",d1.count)
Output
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
- class community:
- def __init__(myself, name, year):
- myself.name = name
- myself.year = year
-
- def myfunc(myself):
- print("Hello World")
-
- p1 = community("C# corner",2019)
- p1.myfunc()
- print("Wellcome to ", p1.name, + p1.year) s
Output
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
- class dog:
- name='Dommy'
- age='4'
- def show(self):
- print (self.name)
- print (self.age)
- d1 = dog()
-
- print (getattr(d1,'name'))
-
-
- print (hasattr(d1,'name'))
-
-
- setattr(d1,'height',152)
-
-
- print (getattr(d1,'height'))
-
-
- delattr(dog,'age')
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.
- __dict__ :To holding the class namespace
- __doc__: To give the class documentation string or None, if #ff0000
- __name__ :It gives the class name
- __module__ :Itprovide module name in which the class is defined
- __bases__ : To give the bases of the class
- class collors:
- 'This is a sample class called collors'
- collorCount=0
- def __int__(self,red,yellow):
- self.red = Apple
- self.yellow = lemon
- collocrCount+=1
- def displayCount(self):
- print("Tottal collorCount %d" %collors.collorCount)
- def displayfruit(self):
- print("Red:", self.red, "Yellow:",self.yellow)
-
- print("collors.__doc__:",collors.__doc__)
- print("Collos.__name__:", collors.__name__)
- print("collors.__module__:", collors.__module__)
- print("collors.__bases__:", collors.__bases__)
- print("collors.__dict__:", collors.__dict__)
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
Def functionname (arguments):
“““Function docstring”””
Statements
Return[expression]
Example
- class Student:
-
- def __init__(self, name):
- print("This is constructor")
- self.name = name
-
- def show(self):
- print("Hello",self.name)
- student = Student("C# corner")
-
- student.show()
Output
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.