0% found this document useful (0 votes)
40 views94 pages

PPL Unit - V

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 94

Principles of Programming Languages

Unit - V
Functional, Logic and
Scripting programming Languages
Functional Programming Languages: Introduction,
Mathematical Functions, Fundamentals of Functional
Programming Language, LISP, Support for Functional
Programming in Primarily Imperative Languages,
Comparison of Functional and Imperative Languages
Logic Programming Language: Introduction, an Overview
of Logic Programming, Basic Elements of Prolog,
Applications of Logic Programming.
Scripting Language: Pragmatics, Key Concepts, Case
Study: Python – Values and Types, Variables, Storage
and Control, Bindings and Scope, Procedural
Abstraction, Data Abstraction, Separate Compilation,
Types of Programming
Languages
1. Procedural programming languages

2. Functional programming languages

3. Object-oriented programming languages (OOP)

4. Scripting languages

5. Logic programming languages

Source:
https://www.coursera.org/articles/types-programming-language
Source:
Source:
https://www.educba.com/types-of-computer-language/
Functional Programming
Language
The design of the imperative languages is based directly on
the von Neumann architecture
Efficiency is the primary concern, rather than the
suitability of the language for software development
The design of the functional languages is based
on mathematical functions
A solid theoretical basis that is also closer to the user, but
relatively unconcerned with the architecture of the
machines on which programs will run
Mathematical Functions - Simple
Functions
A mathematical function is a mapping of members of one
set, called the domain set, to another set, called the range
set
A lambda expression specifies the parameter(s) and the
mapping of a function in the following form
λ(x) x * x * x

for the function cube (x) = x *


x * x where x is a real
Mathematical
Functions
For example, consider the following evaluation of
cube(x):
cube (2.0) = 2.0 * 2.0 * 2.0 = 8
The parameter x is bound to 2.0 during the evaluation
and there are no unbound parameters.
Church defined a formal computation model (a formal
system for function definition, function application, and
recursion) using lambda expressions. This is called
lambda calculus.
Mathematical Functions - Functional
Forms
A higher-order function, or functional form, is one that
either takes one or more functions as parameters or yields
a function as its result, or both.
One common kind of functional form is function
composition, which has two functional parameters and
yields a function whose value is the first actual
parameter function applied to the result of the second.
Function composition is written as an expression, using ° as
an operator
Mathematical Functions - Functional
Forms
Mathematical Functions - Functional
Forms
Apply-to-all is a functional form that takes a single function
as a parameter. If applied to a list of arguments, apply-to-
all applies its functional parameter to each of the values
in the list argument and collects the results in a list or
sequence. Apply-to-all is denoted by ɑ. Consider the
following example:
Fundamentals of Functional Programming
Languages
The objective of the design of a functional programming
language is to mimic mathematical functions to the
greatest extent possible.
This results in an approach to problem solving that is
fundamentally different from approaches used with imperative
languages.
In an imperative language, an expression is evaluated and the
result is stored in a memory location, which is represented as
a variable in a program. This is the purpose of assignment
statements.
Fundamentals of Functional Programming
Languages
A program in an assembly language often must also store
the results of partial evaluations of expressions.
For example, to evaluate
(x + y)/(a - b)
the value of (x + y) is computed first. That value must then
be stored while (a - b) is evaluated.
The compiler handles the storage of intermediate results
of expression evaluations in high-level languages.
The storage of intermediate results is still required, but
the details are
hidden from the programmer.
Fundamentals of Functional Programming
Languages
A purely functional programming language does not use
variables or assignment statements, thus freeing the
programmer from concerns related to the memory cells, or
state, of the program.
A functional language provides a set of primitive functions, a
set of functional forms to construct complex functions from
those primitive functions, a function application
operation, and some structure or structures for
representing data.
These structures are used to represent the parameters
Fundamentals of Functional Programming
Languages
If a functional language is well defined, it requires
only a relatively small number of primitive functions.
The first functional programming language, LISP, uses a
syntactic form, for both data and code, that is very different
from that of the imperative languages.
Many functional languages designed later use syntax for their
code that is similar to that of the imperative languages.
First Functional Programming Language -
LISP
Many functional programming languages have been
developed. The oldest and most widely used is LISP, which
was developed by John McCarthy at MIT in 1959.
LISP was the first functional language, but although it has
steadily evolved for half a century, it no longer represents
the latest design concepts for functional languages.
The original LISP represent well the fundamental concepts of
functional programming and are therefore worthy of study
LISP - Data Types and
Structures
There were only two categories of data objects in the original
LISP:
atoms and lists.
List elements are pairs, where the first part is the data
of the element, which is a pointer to either an atom
or a nested list.
The second part of a pair can be a pointer to an atom, a pointer
to another element, or the empty list.

Elements are linked together in lists with the


second parts. In fact, the original LISP was a
LISP - Data Types and
Structures
Lists are specified in LISP by delimiting their elements
with parentheses. The elements of simple lists are
restricted to atoms,
(A B C D)
Nested list structures are also specified by parentheses.
For example, the list

(A (B C) D (E (F G)))
is a list of four elements. The first is the atom A; the
second is the sublist (B C); the third is the atom D; the
Internal Representation of LISP
List
Internal Representation of LISP
List
LISP
Example
Function calls were specified in a prefix list form
originally called
Cambridge Polish

For example - if + is a function that takes two or more


numeric parameters, the following two expressions
evaluate to 12 and 20

(+ 5 7)
LISP

LISP functions specified in this new notation were


called
S-expressions, for symbolic expressions.
All LISP structures, both data and code, were called
S-expressions.
An S-expression can be either a list or an atom.
We will usually refer to S-expressions simply as
expressions.
LISP

The definition of M-notation, which was the planned


programming notation for LISP, was never completed or
implemented, so
S-expressions became LISP’s only notation
Another feature of early LISP systems that was
apparently accidental was the use of dynamic
scoping.
Contemporary dialects either use static scoping or
allow the programmer to choose between static and
Comparison of Imperative and Functional
Languages

Source:
Comparison of Imperative and Functional
Languages

Source:
Logic Programming
Language
Logic Programming
Language
Programming that uses a form of symbolic logic as
a programming language is often called logic
programming
Languages based on symbolic logic are called logic
programming languages, or declarative languages.
Logic Programming
Language
The approach is to express programs in a form of
symbolic logic and use a logical inferencing process to
produce results.
Programs in logic programming languages
are collections of facts and rules.
Logic programming language - Prolog,
because it is the
only widely used logic language
Logic Programming
Language
The syntax of logic programming languages is
remarkably different from that of the imperative and
functional languages.
The semantics of logic programs also bears little
resemblance to that of imperative-language programs.
These observations should lead the reader to
some curiosity about the nature of logic
programming and declarative languages.
Logic Programming
Language
Languages used for logic programming are called
declarative languages, because programs written in
them consist of declarations rather than assignments
and control flow statements.
These declarations are actually statements, or
propositions, in symbolic logic.
Logic Programming
Language
One of the essential characteristics of logic
programming languages is their semantics, which
is called declarative semantics.
Declarative semantics is considerably simpler
than the semantics of the imperative languages.
For example, the meaning of a given proposition in a
logic programming language can be concisely
determined from the statement itself.
Logic Programming
Language
Programming in both imperative and functional
languages is primarily procedural, which means that
the programmer knows what is to be accomplished by a
program and instructs the computer on exactly how the
computation is to be done.
Programming in a logic programming language is
nonprocedural. Programs in such languages do not state
exactly how a result is to be computed but rather
describe the form of the result.
Logic Programming
Language
An example commonly used to illustrate the difference
between procedural and nonprocedural systems is sorting.
In a language like Java, sorting is done by explaining in
a Java program all of the details of some sorting
algorithm to a computer that has a Java compiler.
The computer, after translating the Java program
into machine code or some interpretive intermediate
code, follows the instructions and produces the
sorted list.
Logic Programming
Language
In a nonprocedural language, it is necessary only to
describe the characteristics of the sorted list:
It is some permutation of the given list such that for
each pair of adjacent elements, a given relationship
holds between the two elements.
To state this formally, suppose the list to be sorted is in
an array named list that has a subscript range 1 . . . n.
Logic Programming
Language
The concept of sorting the elements of the
given list, named old_list, and placing them in
a separate array, named new_list, can then
be expressed as follows:
The Basic Elements of
Prolog
The Basic Elements of
Prolog
There are now a number of different dialects of Prolog.

These can be grouped into several


categories: those that grew from the
Marseille group,
those that came from the Edinburgh
group, and
some dialects that have been developed for
microcomputers, such as micro-Prolog, which is described
The Basic Elements of
Prolog
The syntactic forms of these are somewhat different.
Rather than attempt to describe the syntax of several
dialects of Prolog or some hybrid of them, we have chosen
one particular, widely available dialect, which is the one
developed at Edinburgh.
This form of the language is sometimes called Edinburgh
syntax.
Its first implementation was on a DEC System-10
The Basic Elements of
Prolog
As with programs in other languages, Prolog
programs consist of collections of statements.
There are only a few kinds of statements in Prolog,
but they can be complex.
All Prolog statement, as well as Prolog data, are
constructed from terms.
The Basic Elements of
Prolog
A Prolog term is a constant, a variable, or a structure.
A constant is either an atom or an integer.
Atoms are the symbolic values of Prolog and are
similar to their counterparts in LISP.
In particular, an atom is either a string of letters,
digits, and underscores that begins with a lowercase
letter or a string of any printable ASCII characters
delimited by apostrophes.
The Basic Elements of
Prolog
The last kind of term is called a structure.
Structures represent the atomic propositions of
predicate calculus, and their general form is the
same:
functor(parameter list)
The functor is any atom and is used to identify
the structure.
The parameter list can be any list of atoms, variables,
or other structures.
The Basic Elements of
Prolog
Prolog statements begins with those statements used to
construct the hypotheses, or database of assumed
information - the statements from which new information
can be inferred.
Prolog has two basic statement forms; these correspond
to the
headless and headed Horn clauses of predicate calculus.
The simplest form of headless Horn clause in Prolog is a
single structure, which is interpreted as an
unconditional assertion, or fact.
The Basic Elements of Prolog -
Example
female(shelley).
male(bill).
female(mary).
male(jake).
father(bill, jake).
father(bill, shelley).
mother(mary,
jake).
mother(mary,
The Basic Elements of Prolog -
Example
These simple structures state certain facts
about jake, shelley, bill, and mary.
For example, the first states that shelley is a
female.
The last four connect their two parameters
with a relationship that is named in the
functor atom;
for example - the fifth proposition might be
interpreted to mean that bill is the father of jake.
The Basic Elements of Prolog -
Example
For example, the proposition
father(bill, jake).
could mean bill and jake have the same father or
that jake is the father of bill.
The most common and straightforward meaning,
however, might be that bill is the father of jake.
The Basic Elements of
Prolog
The general form of the Prolog headed Horn
clause statement is
consequence :- antecedent_expression.
It is read as follows: “Consequence can be concluded
if the antecedent expression is true or can be made to
be true by some instantiation of its variables”
The Basic Elements of
Prolog
consequence :- antecedent_expression.
The right side is the antecedent, or if part, and the
left side is the consequent, or then part.
If the antecedent of a Prolog statement is true, then
the consequent of the statement must also be true.
The Basic Elements of
Prolog
For example,
ancestor(mary, shelley) :- mother(mary, shelley).
states that if mary is the mother of shelley, then
mary is an ancestor of shelley.
Headed Horn clauses are called rules, because
they state rules of implication between
propositions.
The Basic Elements of
Prolog
As with clausal form propositions in predicate calculus,
Prolog statements can use variables to generalize their
meaning. Recall that variables in clausal form provide a
kind of implied universal quantifier.
The following demonstrates the use of variables in
Prolog statements:
parent(X, Y) :- mother(X, Y).
parent(X, Y) :- father(X, Y).
grandparent(X, Z) :- parent(X, Y) , parent(Y, Z).
Prolog - Example -
1
As a simple example of the use of numeric
computation in Prolog, consider the following
problem:
Suppose we know the average speeds of several
automobiles on a particular racetrack and the amount
of time they are on the track.
This basic information can be coded as facts, and the
relationship between speed, time, and distance can be
written as a rule, as in the following:
Prolog - Example -
1 speed(ford, 100).
speed(chevy, 105).
speed(dodge, 95).
speed(volvo, 80).
time(ford, 20).
time(chevy, 21).
time(dodge, 24).
time(volvo, 24).
distance(X, Y) :- speed(X, Speed),
time(X, Time),
Y is Speed * Time.
Prolog - Example -
1
Now, queries can request the distance traveled by a
particular car.
For example,
the query distance(chevy,
Chevy_Distance). instantiates
Chevy_Distance with the value 2205.
Prolog - Example -
1
In the following trace example,
a trace of the computation of the value for
Chevy_Distance, the goal requires no redo or fail
events:
trace.
distance(chevy, Chevy_Distance).
Prolog - Example -
1
(1) 1 Call: distance(chevy, _0)?
(2) 2 Call: speed(chevy, _5)?
(3) 2 Exit: speed(chevy, 105)
(4) 2 Call: time(chevy, _6)?
(3) 2 Exit: time(chevy, 21)
(4) 2 Call: _0 is 105*21?
(4) 2 Exit: 2205 is 105*21
(1) 1 Exit: distance(chevy, 2205)
Chevy_Distance = 2205
Prolog - Example -
2
likes(jake,
chocolate).
likes(jake,
apricots).
likes(darcie,
licorice).
likes(darcie,
apricots). trace.
Prolog - Example -
2
(1) 1 Call: likes(jake, _0)?
(1)1 Exit: likes(jake,
chocolate)
(2)1 Call: likes(darcie,
chocolate)?
(2) 1 Fail: likes(darcie,
chocolate)
(1) 1 Redo: likes(jake, _0)?
(1) 1 Exit: likes(jake, apricots)
(3) 1 Call: likes(darcie,
SCRIPTING LANGUAGES
Introduction to Scripting Languages:
Traditional programming languages are concerned with building a self
contained environment that receives input and produces output.
Most “real-world” computing however involves the use of multiple programs
All scripting languages are programming languages.
The scripting language is basically a language where instructions are written for
a run time environment.
They do not require the compilation step and are rather interpreted.
A scripting language is a programming language designed for integrating and
communicating with other programming languages.
Differences between programming and
scripting languages :
Scripting Language Programming Language
1. Scripting languages are 1. Programming languages are
interpreter based languages. compiler based languages.
2. Scripting language 2. Programming language
programs or applications programs requires explicitly
explicitly compilation is not compilation.
required. 3. Programming language
3. Scripting language programs or applications
programs or applications directly we can not run
directly we can run without without compiling.
compiling.
4. Scripting language 4. Programming language
programs or applications programs or applications
takes longer time to takes less time to execute.
execute. 5. For example, C , C++ , Java
5. For example, Shell
Script, Perl
Programming Languages:
Traditional programming languages are concerned with building a
self contained environment that receives input and produces output.
Most “real-world” computing however involves the use of multiple
programs
Languages such as Java stress efficiency, portability and
maintainability.
The programs are based upon hardware-level concepts.
Examples of this include: fixed sized integers, floating point
numbers, characters and arrays.
So how can we re-write the problem? Through the use of a scripting
language.
Scripting languages stress flexibility, rapid development and
dynamic checking.
Their type systems embrace very high level concepts such as tables,
patterns, lists and files.
There a number of distinct groups that fall under the scripting
language family.
Languages such as Perl and Python are known as ``glue’’ languages
because they were designed to glue existing programs together.
Introduction to Python
Python converts source code written by the programmer into
intermediate language which is again translated into the native
language / machine language that is executed. So Python is an
Interpreted language.
Python is a high-level, interpreted, interactive and object oriented-
scripting language.
Python was designed to be highly readable which uses English
keywords frequently where as other languages use punctuation and
it has fewer syntactical constructions than other languages
It is processed at runtime by the interpreter.
The program need not be compiled before its execution.
It is similar to PERL and PHP.
Everything in Python is an object.
The objects can be either mutable or immutable.
A mutable object can be changed after it is created, and an
immutable object can’t.
Python is Interpreted: This means that it is processed at runtime
by the interpreter and you do not need to compile your program
before executing it. This is similar to PERL and PHP.

Python is Interactive: This means that you can actually sit at a


Python prompt and interact with the interpreter directly to write
your programs.
Python is Object-Oriented: This means that Python supports
Object-Oriented style or technique of programming that
encapsulates code within objects.

Python is Beginner's Language: Python is a great language for the


beginner programmers and supports the development of a wide
range of applications, from simple text processing to WWW
browsers to games.
Compiling and interpreting :
Many languages require you to compile (translate) your program
into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class
Python is instead directly interpreted into machine instructions.

interpret
source code output
Hello.py
Features of Python:
Easy-to-learn: Python has relatively few keywords, simple
structure, and a clearly defined syntax.
Easy-to-read: Python code is much more clearly defined and
visible to the eyes.
Easy-to-maintain: Python's success is that its source code is
fairly easy-to-maintain.
A broad standard library: One of Python's greatest strengths is
the bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Support for an interactive mode in which you
can enter results from a terminal right to the language, allowing
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
Extendable: You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases: Python provides interfaces to all major commercial
databases.
GUI Programming: Python supports GUI applications that can
be created and ported to many system calls, libraries, and windows
systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable: Python provides a better structure and support for large
programs than shell scripting.
Script Mode Programming :
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is finished.
When the script is finished, the interpreter is no longer active.

For example, put the following in one test.py, and run,


print "Hello, Python!";
print "I love COMP3050!";

The output will be:


Hello, Python!
I love COMP3050!
Define Identifier in python.
A Python identifier is a name used to identify a variable, function,
class, module, or other object. An identifier starts with a letter A to
Z or a to z or an underscore (_) followed by zero or more letters,
underscores, and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and %


within identifiers. Python is a case sensitive programming language.
Thus Manpower and manpower are two different identifiers in
Python
Note:
Here are following identifier naming convention for Python:
Class names start with an uppercase letter and all other
identifiers with a lowercase letter.
Starting an identifier with a single leading underscore indicates
by convention that the identifier is meant to be private.
Starting an identifier with two leading underscores indicates a
strongly private identifier.
If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name
Keywords contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Define variable in python.
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space
in memory.
Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.
Python variables do not have to be explicitly declared to reserve
memory space. The declaration happens automatically when you
assign a value to a variable. The equal sign (=) is used to assign
values to variables.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
You can also assign a single value to several variables
simultaneously. For example:
a=b=c=1
a, b, c = 1, 2, "john"
Data types in python:
Python has five standard data types.
Numbers
String
List
Tuple
Dictionary
Number data types store numeric values. They are
immutable data types, which means that changing
the value of a number data type results in a newly
allocated object.
Number objects are created when you assign a value
to them. For example:
var1 = 1
var2 = 10
Python supports four different numerical types:
Int, long, float and complex.
Define string:
Strings in Python are identified as a contiguous set of characters in
between quotation marks.
Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ( [ ] and [ : ] ) with
indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
The plus ( + ) sign is the string concatenation operator, and the
asterisk ( * ) is the repetition operator.
Example:
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
List in python:
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square
brackets ([]).
To some extent, lists are similar to arrays in C. One difference
between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator
( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list
and working their way to end-1.
The plus ( + ) sign is the list concatenation operator, and the asterisk
( * ) is the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john‘]
Tuple in Python:
A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed
in brackets ( [ ] ), and their elements and size can be changed, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists.
Example:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john‘)
Dictionary in Python:
Python 's dictionaries are hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs.
Keys can be almost any Python type, but are usually numbers or
strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ( { } ) and values can be
assigned and accessed using square braces ( [] ).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john‘]
SCOPE OF VARIABLE:
The scope of a variable determines the portion of the program
where you can access a particular identifier.
There are two basic scopes of variables in Python:
Global variables
Local variables
Global vs. Local variables:
Scope of a variable is the region in the code where the variable is
available/accessible.
A variable declared outside a function (i.e. the main region of the
code) is called a global variable.
a variable declared inside a function is called a local variable of
that function.
When you call a function, the variables declared inside it are
brought into scope.
Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total ;
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total;
This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
# Uses global because there is no local 'a'
a=1
def f():
print('Inside f() : ', a)
# Variable 'a' is redefined as a local
def g():
a=2
print('Inside g() : ', a)
# Uses global keyword to modify global 'a'
def h():
global a
a=3
print('Inside h() : ', a)
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Define Abstraction.:
an abstraction is used to hide the irrelevant data/class in order to
reduce the complexity.
It also enhances the application efficiency.
Procedural abstraction:
Procedural abstraction is when we write code sections (called
"procedures" or in Java, "static methods") which are generalized by
having variable parameters.
The idea is that we have code which can cope with a variety of
different situations, depending on how its parameters are set when it
is called.
Example: In Python when we write from math import log; print log(2) we really
don't care about how log function is implemented in math library.
Data abstraction:
Data abstraction is one of the most essential concepts of Python ,which is
used to hide irrelevant details from the user and show the details that are
relevant to the users.

A simple example of this can be a car.


A car has an accelerator, clutch, and break and we all know that pressing
an accelerator will increase the speed of the car and applying the brake can
stop the car but we don't know the internal mechanism of the car and
how these functionalities can work this detail hiding is known as data
abstraction.
It enables programmers to hide complex implementation details
while just showing users the most crucial data and functions.

This abstraction makes it easier to design modular and well-


organized code, makes it simpler to understand and maintain,
promotes code reuse, and improves developer collaboration.
we can achieve data abstraction by using abstract classes
To create an abstract class in Python, it must inherit the ABC class
that is defined in the ABC module. This module is available in
Python's standard library.
Moreover, the class must have at least one abstract method.
Again, an abstract method is the one which cannot be called but can
be overridden.
You need to decorate it with @abstractmethod decorator.
Create an abstract class:
from abc import ABC, abstractmethod
class demo(ABC):
@abstractmethod
def method1(self):
print ("abstract method")
return
def method2(self):
print ("concrete method“)

You might also like