Introduction to Object Oriented Programming: Object-oriented vs Procedure-oriented Programming languages: 1. Object-oriented programming is the problem-solving approach and used where computation is done by using objects. Procedural programming uses a list of instructions to do computation step by step. 2. It makes the development and maintenance easier. In procedural programming, It is not easy to maintain the codes when the project becomes lengthy. 3. It simulates the real world entity. So real-world problems can be easily solved through oops.It doesn't simulate the real world. It works on step by step instructions divided into small parts called functions. 4. It provides data hiding. So it is more secure than procedural languages. You cannot access private data from anywhere. Procedural language doesn't provide any proper way for data binding, so it is less secure. 5. Example of object-oriented programming languages is C++, Java, .Net, Python, C#, etc. Examples of procedural languages are: C, Fortran, Pascal, VB etc. Class: The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. It specifies the set of instance variables and methods that are bundle together for defining a type of object. For example: if you have an employee class then it should contain an attribute and method, i.e. an email id, name, age, salary, etc. Syntax class ClassName: <statement-1> . . <statement-N> The class keyword is used to define classes, much as def is used for defining functions. class ClassName: Data members methods() For example, strings in Python are object instances of the built-in String class, depicted in Figure 1. Figure 1: Object Instances of String Class
34
Embed
Introduction to Object Oriented Programming · 2020. 9. 12. · Introduction to Object Oriented Programming: Object-oriented vs Procedure-oriented Programming languages: 1. Object-oriented
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Introduction to Object Oriented Programming:
Object-oriented vs Procedure-oriented Programming languages:
1. Object-oriented programming is the problem-solving approach and used where computation
is done by using objects.
Procedural programming uses a list of instructions to do computation step by step.
2. It makes the development and maintenance easier.
In procedural programming, It is not easy to maintain the codes when the project becomes
lengthy.
3. It simulates the real world entity. So real-world problems can be easily solved through oops.It
doesn't simulate the real world.
It works on step by step instructions divided into small parts called functions.
4. It provides data hiding. So it is more secure than procedural languages. You cannot access
private data from anywhere.
Procedural language doesn't provide any proper way for data binding, so it is less secure.
5. Example of object-oriented programming languages is C++, Java, .Net, Python, C#, etc.
Examples of procedural languages are: C, Fortran, Pascal, VB etc.
Class:
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. It specifies the set of instance variables and methods that are
bundle together for defining a type of object. For example: if you have an employee class then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName: <statement-1> . . <statement-N>
The class keyword is used to define classes, much as def is used for defining functions. class ClassName:
Data members
methods()
For example, strings in Python are object instances of the built-in String class, depicted in
Figure 1.
Figure 1: Object Instances of String Class
One method of the String class is isdigit(). Thus, every string object has this
method. The specific object whose isdigit() method is called determines the specific
print('Object with name %s goes out of scope'%self.name) p1=Person('john',28) p1.display()
p2=Person('Raju',30) p2.display()
p3=Person('Rani',29) p3.display() print(p1)
del p1 del p2
del p3 print(p2) """
OUTPUT: 1 Name: john Age: 28 2 Name: Raju Age: 30
3 Name: Rani Age: 29 <__main__.Person object at 0x01C9B5C8>
Object with name john goes out of scope Object with name Raju goes out of scope Object with name Rani goes out of scope
Traceback (most recent call last): File "G:\2020-21-Online Classes\DSP\19-08-2020\Persondel.py", line 26, in
<module> print(p2) NameError: name 'p2' is not defined
""" Three Fundamental Features of Object oriented Programming:
Inheritance:
Inheritance is the most important aspect of object-oriented programming which simulates
the real world concept of inheritance. It specifies that the child object acquires all the properties
and behaviours of the parent object.
By using inheritance, we can create a class which uses all the properties and behaviour of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
It provides re-usability of the code.
Polymorphism:
Polymorphism contains two words "poly" and "morphs". Poly means many and Morphs
means form, shape. By polymorphism, we understand that one task can be performed in
different ways. For example You have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behaviour is polymorphic in the sense and depends on the animal.
So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs and
cats) have a concrete implementation of the action "speak".
Encapsulation:
Encapsulation is also an important aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped together
within a single unit from being modified by accident.
Data Abstraction:
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonym because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a function
or a whole program does.
Data Abstraction and Hiding through Classes:
Data Abstraction:
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonym because data abstraction is achieved through encapsulation.
Abstraction in Python is the process of hiding the real implementation of an application
from the user and emphasizing only on usage of it.
For example, consider you have bought a new electronic gadget. Along with the gadget,
you get a user guide, instructing how to use the application, but this user guide has no info
regarding the internal working of the gadget.
Another example is, when you use TV remote, you do not know how pressing a key in the
remote changes the channel internally on the TV. You just know that pressing + volume key will
increase the volume.
A programmer can hide all the irrelevant data/process of an application in order to reduce
complexity and increase efficiency. In Python, abstraction can be achieved by using abstract
classes and methods in our programs.
A class containing at least one or more abstract methods is called an abstract class. An
abstract class just serves as a template for other classes by defining a list of methods that the
classes must implement.
Abstract methods do not contain any implementation. Instead, all the implementations
can be defined in the methods of sub-classes that inherit the abstract class. An abstract class
is created by importing a class named 'ABC' from the 'abc' module and inheriting the 'ABC'
class. Below is the syntax for creating the abstract class.
An abstract class can have both a normal method and an abstract method
An abstract class cannot be instantiated, ie., we cannot create objects for the abstract
class.
Syntax:
from abc import ABC,abstractmethod
Class ClassName(ABC):
Where ABC is an abstract base class.
Example:
from abc import ABC, abstractmethod class Shape(ABC): def display(self):#concrete Method or normal Method
print("I am a normal method defined inside the abstract class 'Shape'") @abstractmethod def calculate_area(self):#abstract Method pass class Rectangle(Shape): length = 5 breadth = 3 def calculate_area(self): return self.length * self.breadth class Circle(Shape): radius = 4 def calculate_area(self):
return 3.14 * self.radius * self.radius #s=Shape() #s.display() rec = Rectangle() #object created for the class 'Rectangle' rec.display() print("Area of a rectangle:", rec.calculate_area()) #call to 'calculate_area' method defined inside the class 'Rectangle' cir = Circle() #object created for the class 'Circle' print("Area of a circle:", cir.calculate_area()) """ OUTPUT: I am a normal method defined inside the abstract class 'Shape' Area of a rectangle: 15 Area of a circle: 50.24 """
Public and Private data members:
Classical object-oriented languages, such as C++ and Java, control the access to
class resources by public, private and protected keywords.
Private members of a class are denied access from the environment outside the
class. They can be handled only from within the class.
Public members (generally methods declared in a class) are accessible from
outside the class. The object of the same class is required to invoke a public method.
This arrangement of private instance variables and public methods ensures the
principle of data encapsulation.
Protected members of a class are accessible from within the class and are also
available to its sub-classes. No other environment is permitted access to it. This
enables specific resources of the parent class to be inherited by the child class.
Python doesn't have any mechanism that effectively restricts access to any
instance variable or method. Python prescribes a convention of prefixing the name of
the variable/method with single or double underscore to emulate the behaviour of
protected and private access specifiers.
All members in a Python class are public by default. Any member can be
accessed from outside the class environment.
Python's convention to make an instance variable protected is to add a prefix _
(single underscore) to it. This effectively prevents it to be accessed, unless it is from
within a sub-class.
Similarly, a double underscore __ prefixed to a variable makes it private. It gives a
strong suggestion not to touch it from outside the class. Any attempt to do so will result
in an AttributeError:
We can access private variables from outside of the class using following syntax.
class Encap: def __init__(self,num1,num2): self.num1=num1 self.__num2=num2 def display(self): print("Number1 value is:",self.num1) print("Number1 value is:",self.__num2) e=Encap(10,20) e.display() print("From the main module,Number1 is:",e.num1) #print("From the main module,Number2 is:",e.__num2) print("From the main module,Number2 is:",e._Encap__num2) """ OUTPUT: Number1 value is: 10 Number2 value is: 20 From the main module,Number1 is: 10 From the main module,Number2 is: 20 """
ENCAPSULATION (Data Hiding):
Encapsulation is a means of bundling together instance variables and methods to
form a given type (class). Selected members of a class can be made inaccessible
(“hidden”) from its clients, referred to as information hiding. Information hiding is a
form of abstraction. This is an important capability that object-oriented programming
languages provide. As an example, we give a depiction of a Fraction object in Figure 2.
Figure 2: Fraction Object Access
The Fraction object shows private instance variables __numerator and __denominator, and
four public methods.Private members of a class begin with two underscore characters, and
cannot be directly accessed. For example, trying to access the instance variables of Fraction
object frac1 is invalid,
frac1.__numerator =4 NOT ALLOWED
frac1.__denominator= 6 NOT ALLOWED
Public members of a class, on the other hand, are directly accessible. For example, the
following are valid method calls,
frac1.getNumerator() ALLOWED
frac1.getDenominator() ALLOWED
frac1.setNumerator(4) ALLOWED
frac1.setDenominator(6) ALLOWED
These methods are referred to as getters and setters since their purpose is to get (return)
and set (assign) private instance variables of a class. Restricting access to instance variables via
getter and setter methods allows the methods to control what values are assigned (such as not
allowing an assignment of 0 to the denominator), and how they are represented when retrieved.
Thus, the instance variables of a class are generally made private, and the methods of the class
A method in the derived calls is always called before the method of the base class.
In our example, Dog class is called before NonMarineMammal or NoneWingedMammal.
These two classes are called before Mammal, which is called before Animal, and
Animal class is called before the object.
If there are multiple parents like Dog(NonMarineMammal, NonWingedMammal),
methods of NonMarineMammal is invoked first because it appears first.
Polymorphism:
Polymorphism is taken from the Greek words Poly (many) and morphism (forms). It
means that the same function name can be used for different types. This makes
programming more intuitive and easier.
In Python, we have different ways to define polymorphism. So let’s move ahead and
see how polymorphism works in Python.
Polymorphism in Python:
A child class inherits all the methods from the parent class. However, in some
situations, the method inherited from the parent class doesn’t quite fit into the child
class. In such cases, you will have to re-implement method in the child class.
Polymorphism with Inheritance:
Polymorphism in python defines methods in the child class that have the same name
as the methods in the parent class. In inheritance, the child class inherits the methods
from the parent class. Also, it is possible to modify a method in a child class that it has
inherited from the parent class.
This is mostly used in cases where the method inherited from the parent class
doesn’t fit the child class. This process of re-implementing a method in the child class is
known as Method Overriding. Here is an example that shows polymorphism with
inheritance.
Example:
class Animal: def __init__(self,n,a):
self.name=n self.age=a
def display(self): pass def sound(self):
pass
class Cat(Animal): def __init__(self,n,a): super().__init__(n,a)
def display(self): print('I am cat.My name is',self.name,'and i am',self.age,'years old')
def sound(self):
print('MEOW MEOW') class Dog(Animal):
def __init__(self,n,a): super().__init__(n,a)
def display(self): print('I am Dog.My name is',self.name,'and i am',self.age,'years old') def sound(self):
print('BOW BOW') c=Cat('Lucy',5)
c.display() c.sound()
d=Dog('puppy',6) d.display() d.sound()
'''
OUTPUT: I am cat.My name is Lucy and i am 5 years old MEOW MEOW
I am Dog.My name is puppy and i am 6 years old BOW BOW ''' Abstract Class and Interface:
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonym because data abstraction is achieved through encapsulation.
Abstraction in Python is the process of hiding the real implementation of an application from
the user and emphasizing only on usage of it.
For example, consider you have bought a new electronic gadget. Along with the gadget, you
get a user guide, instructing how to use the application, but this user guide has no info regarding
the internal working of the gadget.
Another example is, when you use TV remote, you do not know how pressing a key in the
remote changes the channel internally on the TV. You just know that pressing + volume key will
increase the volume.
A programmer can hide all the irrelevant data/process of an application in order to reduce
complexity and increase efficiency. In Python, abstraction can be achieved by using abstract
classes and methods in our programs.
A class containing at least one or more abstract methods is called an abstract class. An
abstract class just serves as a template for other classes by defining a list of methods that the
classes must implement.
Abstract methods do not contain any implementation. Instead, all the implementations can
be defined in the methods of sub-classes that inherit the abstract class. An abstract class is
created by importing a class named 'ABC' from the 'abc' module and inheriting the 'ABC' class. We
can use NotImplementedError to restrict the instantiation of a class. Any class that has
NotImplementedError inside the method definition cannot be instantiated.
An abstract class can have both a normal method and an abstract method
An abstract class cannot be instantiated, ie., we cannot create objects for the abstract class.
An interface acts as a blueprint for designing classes. Like classes, interfaces define
methods. Unlike classes, these methods are abstract. An abstract method is one that the interface
simply defines. It doesn’t implement the methods. This is done by classes, which then implement
the interface and give concrete meaning to the interface’s abstract methods .An interface has only
abstract methods.
Example1:
from abc import ABC, abstractmethod class Shape(ABC): def display(self):#concrete Method or normal Method print("I am a normal method defined inside the abstract class 'Shape'") @abstractmethod def calculate_area(self):#abstract Method pass class Rectangle(Shape): length = 5 breadth = 3 def calculate_area(self): return self.length * self.breadth class Circle(Shape): radius = 4 def calculate_area(self): return 3.14 * self.radius * self.radius #s=Shape() #s.display() rec = Rectangle() #object created for the class 'Rectangle' rec.display() print("Area of a rectangle:", rec.calculate_area()) #call to 'calculate_area' method defined inside the class 'Rectangle' cir = Circle() #object created for the class 'Circle' print("Area of a circle:", cir.calculate_area()) """ OUTPUT: I am a normal method defined inside the abstract class 'Shape' Area of a rectangle: 15 Area of a circle: 50.24 """ Example2: