0% found this document useful (0 votes)
7 views15 pages

Python Functions and Functional Programming

This document provides an overview of functions and functional programming in Python, detailing their creation, invocation, and characteristics. It explains the differences between functions and procedures, return values, calling conventions, and the use of decorators. Additionally, it covers built-in functions like apply(), filter(), map(), and reduce(), along with examples of their usage.

Uploaded by

sudhashri1203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Python Functions and Functional Programming

This document provides an overview of functions and functional programming in Python, detailing their creation, invocation, and characteristics. It explains the differences between functions and procedures, return values, calling conventions, and the use of decorators. Additionally, it covers built-in functions like apply(), filter(), map(), and reduce(), along with examples of their usage.

Uploaded by

sudhashri1203
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-IV

FUNCTIONS AND FUNCTIONAL PROGRAMMING


Functions in Python support a variety of invocation styles and argument types, including some
functional programming interfaces.
FUNCTIONS
1. EXPLAIN ABOUT FUNCTIONS. (PART-B)
WHAT ARE FUNCTIONS?
Functions are the structured or procedural programming way of organizing the logic in our programs.
Large code blocks can be neatly divided into manageable chunks, and by placing frequently used code in
functions rather than multiple copies everywhere, space is saved.
This also improves consistency because altering a single copy eliminates the need to find and update
multiple copies of duplicate code. Functions can appear in different ways ... here is an example for how
the functions created, used, or otherwise referenced:
1. declaration/definition:
def foo():
print('Welcome to College')
2. function object/reference: foo
3. function call/invocation: foo()
FUNCTIONS VERSUS PROCEDURES
Functions are often compared to procedures. Both are entities that can be invoked, but functions taking
some parameters, performs some amount of processing, and concludes by sending back a return value.
Some functions are Boolean in nature, returning a "yes" or "no" answer, or, more appropriately, a non-
zero or zero value, respectively.
Procedures are simply special cases, functions that do not return a value.
Python procedures are implied functions because the interpreter implicitly returns a default value of
None.
RETURN VALUES AND FUNCTION TYPES
Functions may return a value back to their callers and those that are more procedural in nature do not
explicitly return anything at all.
Languages that treat procedures as functions usually have a special type or value name for functions that
"return nothing". In Python, the equivalent return object type is None.
For example, the hello() function acts as a procedure in the code below, returning no value.
>>> def hello():
... print('hello world')
>>>
>>> res = hello()
hello world
>>> res
>>> print(res)
None
>>> type(res)
<Class 'NoneType'>
One difference is that in returning a container type, it will seem as if you can actually return more than a
single object.
>>>def foo():
…return ['xyz', 1000000, -98.6]
>>>def bar():
…return 'abc', [42, 'python'], "Guido"
The foo() function returns a list, and the bar() function returns a tuple. Because of the tuple's syntax of
not requiring the enclosing parentheses, it creates the perfect illusion of returning multiple items. If we
were to properly enclose the tuple items, the definition of bar() would look like this:
>>>def bar():
…return ('abc', [4-2j, 'python'], "Guido")
As far as return values are concerned, tuples can be saved in a number of ways. The following three
52

Downloaded by priya loganathan (priyacs104@[Link])


ways of saving the return values are equivalent:
>>> aTuple = bar()
>>> x, y, z = bar()
>>> (a, b, c) = bar()
>>>
>>> aTuple
('abc', [(4-2j), 'python'], 'Guido')
>>> x, y, z
('abc', [(4-2j), 'python'], 'Guido')
>>> (a, b, c)
('abc', [(4-2j), 'python'], 'Guido')
In the assignments for x, y, z, and a, b, c, each variable will receive its corresponding return value in the
order the values are returned. The aTuple assignment takes the entire implied tuple returned from the
function.
Recall that a tuple can be "unpacked" into individual variables or not at all and its reference assigned
directly to a single variable.
Return Values and Types
Stated Number of Objects to Return Type of Object That Python Returns
0 None
1 Object
>1 Tuple
CALLING FUNCTIONS
2. HOW DO YOU CALL A FUNCTION? (PART-B)
FUNCTION OPERATOR
Functions are called using the same pair of parentheses that you are used to. In fact, some consider ( () )
to be a two-character operator, the function operator. Any input parameters or arguments must be placed
between these calling parentheses.
Parentheses are also used as part of function declarations to define those arguments.
KEYWORD ARGUMENTS
The concept of keyword arguments applies only to function invocation. The idea here is for the caller to
identify the arguments by parameter name in a function call.
For a simple example, imagine a function foo(), which has the following pseudocode definition:
i. Standard calls to foo(): foo(42) foo('bar') foo(y)
ii. Keyword calls to foo(): foo(x=42) foo(x='bar') foo(x=y)
Keyword arguments may also be used when arguments are allowed to be "missing." These are related to
functions that have default arguments.
DEFAULT ARGUMENTS
Default arguments are those that are declared with default values. Parameters that are not passed on a
function call are thus allowed and are assigned the default value.
GROUPED ARGUMENTS
Python also allows the programmer to execute a function without explicitly specifying individual
arguments in the call as long as you have grouped the arguments in either a tuple (non-keyword
arguments) or a dictionary (keyword arguments).
Basically, put all the arguments in either a tuple or a dictionary (or both), and just call a function with
those buckets of arguments and not have to explicitly put them in the function call:
o func(*tuple_grp_nonkw_args, **dict_grp_kw_args)
The tuple_grp_nonkw_args are the group of non-keyword arguments as a tuple, and the
dict_grp_kw_args are a dictionary of keyword arguments.
CREATING FUNCTIONS
3. HOW TO CREATE A FUNCTION? (PART-B/C)
4. COMMENT ON DEF STATEMENT. (PART-B)
DEF STATEMENT
Functions are created using the def statement, with a syntax like the following:
def function_name(arguments):

53

Downloaded by priya loganathan (priyacs104@[Link])


"function_documentation_string"
function_body_suite
The header line consists of the def keyword, the function name, and a set of arguments (if any).
The remainder of the def clause consists of an optional documentation string and the required function
body suite.
For example:
1) def greet():
print('Hello World!')
Output: Hello World!

2) def hello(who):
print('Hello' + ' ' + str(who))
DECLARATION VERSUS DEFINITION
A function declaration consists of providing the parser with the function name, and the names (and
traditionally the types) of its arguments, without necessarily giving any lines of code for the function,
which is usually referred to as the function definition.
FORWARD REFERENCES
Python does not permit you to reference or call a function before it has been declared. We can try a few
examples to illustrate this:
>>>def foo():
…print('in foo()')
bar()
If we were to call foo() here, it would fail because bar() has not been declared yet:
>>> foo()
in foo()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
foo()
File "<pyshell#3>", line 3, in foo
bar()
NameError: name 'bar' is not defined

FUNCTION ATTRIBUTES
Every function has a number of additional attributes which can be accessed using dot syntax
(e.g. func. name ). The dir built-in function returns a list of available attributes of a specified object.
def func():
print(func.a)
func.a -= 10
func.a = 10
[Link] = "bar"
func()
func.a += 2
func()
print(func. dict )
Internally, it's just a dictionary that handles failed attribute lookups (i.e., nondefault attributes). You can
access or even replace such dictionary using dict attribute.
INNER OR NESTED FUNCTIONS
Inner functions, also known as nested functions, are functions that you define inside other functions.
In Python, this kind of function can access names in the enclosing function. Here’s an example of how to
create an inner function in Python:
>>> def outer_func():
... def inner_func():
... print("Hello, World!")

54

Downloaded by priya loganathan (priyacs104@[Link])


... inner_func()
...
>>> outer_func()
Hello, World!
The scope of a variable is the location where we can find a variable and access it if necessary. The
following program demonstrates the scope of the nested functions:
>>>def outerFunc():
… sample_str = 'Hello Python'
… def innerFunc():
… print(sample_str)
… innerFunc()
>>>outerFunc()
Hello Python
Inner functions turn into something special called closures if the definition of an inner function contains
a reference to an object defined in an outer function.
*FUNCTION (AND METHOD) DECORATORS
Decorators are just "overlays" on top of function calls. These overlays are just additional calls that are
applied when a function or method is declared.
The syntax for decorators uses a leading "at-sign" ( @ ) followed by the decorator function name and
optional arguments. The line following the decorator declaration is the function being decorated, along
with its optional arguments. It looks something like this:
@decorator(dec_opt_args)
def func2Bdecorated(func_opt_args):
The staticmethod() built-in function is then used to "convert" the function into a static method. With
decorators, we can write the piece of code with the following:
class MyClass(object):
@staticmethod
def staticFoo():
Furthermore, decorators can be "stacked" like function calls, so here is a more general example with
multiple decorators:
@deco2
@deco1
def func(arg1, arg2, ...): pass
This is equivalent to creating a composite function:
def func(arg1, arg2, ...): pass
func = deco2(deco1(func))
Decorators With and Without Arguments
Without arguments, a decorator like:
@deco
def foo(): pass
However, a decorator decomaker() with arguments:
@decomaker(deco_args)
def foo(): pass
In other words, decomaker() does something with deco_args and returns a function object that is a
decorator that takes foo as its argument. To put it simply:
foo = decomaker(deco_args)(foo)
Here is an example featuring multiple decorators in which one takes an argument:
@deco1(deco_arg)
@deco2
def func(): pass
This is equivalent to:
func = deco1(deco_arg)(deco2(func))
So What Are Decorators?
The use of decorators are:
1. Introduce logging
55

Downloaded by priya loganathan (priyacs104@[Link])


2. Insert timing logic (aka instrumentation) for monitoring performance
3. Add transactional capabilities to functions
The ability to support decorators is very important for creating enterprise applications in Python.
Decorator Example
def make_pretty(func):
def inner():
print("Example for Decorator")
func()
return inner
@make_pretty
def ordinary():
print("Example for Ordinary")
ordinary()
Output:
Example for Decorator
Example for Ordinary
PASSING FUNCTIONS
5. HOW DO YOU PASS SOMETHING INTO A FUNCTION IN PYTHON? (PART-B)
The one unique characteristic of functions which may set them apart from other objects is that they are
callable, i.e., they can be invoked via the function operator.
>>> def foo():
... print('in foo()')
...
>>> bar = foo
>>> bar()
in foo()
When we assigned foo to bar, we are assigning the same function object to bar, thus we can invoke bar()
in the same way we call foo(). The difference between "foo" (reference of the function object) and
"foo()" (invocation of the function object).

Example: Passing and Calling Functions


def convert(func, seq):
return [func(eachNum) for eachNum in seq]
myseq = (123, 45.67, -6.2e4)
print(convert(int, myseq))
print(convert(float, myseq))
If we were to run this program, we would get the following output:
[123, 45, -62000]
[123.0, 45.67, -62000.0]
BUILT-IN FUNCTIONS: APPLY(), FILTER(), MAP(), REDUCE()
Functional Programming Built-in Functions
Built-in Function Description
apply( func[, nkw][, kw ]) Calls func with optional arguments, nkw for non-keyword arguments and kw
for keyword arguments; the return value is the return value of the function
call.
filter( func, seq) Invokes Boolean function func iteratively over each element of seq; returns a
sequence for those elements for which func returned true.
map( func, seq1[, seq2...]) Applies function func to each element of given sequence(s) and provides
return values in a list; if func is None, func behaves as the identity function,
returning a list consisting of n-tuples for sets of elements of each sequence.
reduce(func, seq[, init]) Applies binary function func to elements of sequence seq, taking a pair at a
time, continually applying the current result with the next value to obtain the
succeeding result, finally reducing our sequence to a single return value; if
initial value init given, first compare will be of init and first sequence element

56

Downloaded by priya loganathan (priyacs104@[Link])


rather than the first two sequence elements.
1. FILTER( )
6. COMMENT ON FILTER( ). (PART-B)
The filter() function facilitates a functional approach to Python programming. It takes as an argument
a function and an iterable and applies the passed function to each element of the iterable. Once this is
done, it returns an iterable.
The filter() function takes the following two arguments as input:
1. function: A valid, pre-defined function. This is a lambda function in most cases.
2. iterable: This is an iterable object (e.g. list, tuple, dictionary).
For example:
def multiple(n):
if(n % 5 == 0):
return n
myList = [10, 25, 17, 9, 30, -5]
myList2 = list(filter(multiple, myList))
print(myList2)
How the filter( ) built-in function works

The above diagram shows our original sequence at the top, items seq[0], seq[1], ... seq[N-1] for a
sequence of size N. For each call to bool_func(), i.e., bool_func (seq [0]), bool_func (seq [1]), etc., a
return value of False or true comes back.
If bool_func() returns True for any sequence item, that element is inserted into the return sequence.
When iteration over the entire sequence has been completed, filter() returns the newly created sequence.
We present below a script that shows one way to use filter() to obtain a short list of random odd
numbers. The script generates a larger set of random numbers first, then filters out all the even numbers,
leaving us with the desired dataset. For example:
from random import randint
def odd(n):
return n % 2
allNums = []
for eachNum in range(9):
[Link](randint(1, 99))
print(list(filter(odd, allNums)))
This code consists of two functions: odd(), a Boolean function that determined if an integer was odd
(true) or even (false), and main(), the primary driving component. The purpose of main() is to generate
ten random numbers between 1 and 100; then filter() is called to remove all the even numbers.
Finally, the set of odd numbers is displayed, preceded by the size of our filtered list.
Refactoring Pass 1
Function odd() is replaced by a lambda expression:
from random import randint
allNums = []
for eachNum in range(9):
[Link](randint(1, 99))
print(list(filter(lambda n: n%2, allNums)))
Refactoring Pass 2

57

Downloaded by priya loganathan (priyacs104@[Link])


How list comprehensions can be a suitable replacement for filter() so here it is:
from random import randint
allNums = []
for eachNum in range(9):
[Link](randint(1, 99))
print([n for n in allNums if n%2])
Refactoring Pass 3
We can further simplify our code by integrating another list comprehension to put together our final list.
from random import randint as ri
print([n for n in [ri(1,99) for i in range(9)] if n%2])
2. MAP( )
7. DEFINE MAP( ). (PART-B)
The map() built-in function is similar to filter() in that it can process a sequence through a function.
However, unlike filter(), map() "maps" the function call to each sequence item and returns a list
consisting of all the return values.
In its simplest form, map() takes a function and sequence, applies the function to each item of the
sequence, and creates a return value list that is comprised of each application of the function.
How the map() built-in function works

We can whip up a few quick lambda functions to show you how map() works on real data:
>>> list(map((lambda x: x+2), [0, 1, 2, 3, 4, 5]))
[2, 3, 4, 5, 6, 7]
>>>
>>> list(map(lambda x: x**2, range(6)))
[0, 1, 4, 9, 16, 25]
>>> [x+2 for x in range(6)]
[2, 3, 4, 5, 6, 7]
>>>
>>>[x**2 for x in range(6)]
[0, 1, 4, 9, 16, 25]
The more general form of map() can take more than a single sequence as its input. If this is the case, then
map() will iterate through each sequence in parallel.
On the first invocation, it will bundle the first element of each sequence into a tuple, apply the func
function to it, and return the result as a tuple into the mapped_seq mapped sequence that is finally
returned as a whole when map() has completed execution.
How the map() built-in function works with > 1 sequence

58

Downloaded by priya loganathan (priyacs104@[Link])


Here are several examples using map() with multiple sequences:
>>> list(map(lambda x, y: x + y, [1,3,5], [2,4,6]))
[3, 7, 11]
>>>
>>> list(map(lambda x, y: (x+y, x-y), [1,3,5], [2,4,6]))
[(3, -1), (7, -1), (11, -1)]
>>>
3. REDUCE( )
8. COMMENT ON REDUCE( ). (PART-B)
The final functional programming piece is reduce(), which takes a binary function, a sequence, and an
optional initializer, and methodologically "reduces" the contents of that list down to a single value, hence
its name. It is also known as folding.
Steps for using Python's reduce function are mentioned below:
1. The iterable's first two elements are subject to the function passed as an argument.
2. The function is then applied to both the most recent result that was generated and the subsequent
element in the iterable.
3. The iterable is processed until the end of this process.
4. Applying the reduce function to the iterable causes the single value to be returned.
For example:
from functools import reduce
def sum(a,b):
return a+b
res = reduce(sum, [2, 5, 3, 7])
print(res)
How the reduce() built-in function works

59

Downloaded by priya loganathan (priyacs104@[Link])


Using a lambda function
In this example, we have defined a lambda function that calculates the sum of two numbers on the
passed list as an iterable using the reduce function.
from functools import reduce
nums = [1, 2, 3, 4]
ans = reduce(lambda x, y: x + y, nums)
print(ans)
Output:
10
The above python program returns the sum of the whole list as a single value result which is calculated
by applying the lambda function, which solves the equation (((1+2)+3)+4).
Using a pre-defined function
Now, a pre-defined function, product, which returns the product of 2 numbers passed into it, is used as
an argument in the reduce function, which is passed along with a list of numbers.
from functools import reduce
def product(x,y):
return x*y
ans = reduce(product, [2, 5, 3, 7])
print(ans)
Output:
210
We get the result as 210 because the steps followed by the reduce function calculate the result of the
following equation(((2x5)x3)x7). First, the multiplication of 2 and 5 is done, and the result of this
multiplication is further done with all the other elements of the list one by one.
MODULES
9. DISCUSS ABOUT MODULES. (PART-B)
WHAT ARE MODULES?
• A module allows to logically organizing our Python code. When code gets to be large enough, the
tendency is to break it up into organized pieces that can still interact with one another at a functioning
level.
• These pieces generally have attributes that have some relation to one another, perhaps a single class with
its member data variables and methods, or maybe a group of related, yet independently operating
functions.
• These pieces should be shared, so Python allows a module the ability to "bring in" and use attributes

60

Downloaded by priya loganathan (priyacs104@[Link])


from other modules to take advantage of work that has been done, maximizing code reusability. This
process of associating attributes from other modules with our module is called importing.
MODULES AND FILES
10. EXPLAIN ABOUT MODULES AND FILES. (PART-B/C)
If modules represent a logical way to organize our Python code, then files are a way to physically
organize modules. To that end, each file is considered an individual module, and vice versa.
The filename of a module is the module name appended with the .py file extension.
MODULE NAMESPACES
The basic concept of a namespace is an individual set of mappings from names to objects. The name of
the attribute is always prepended with the module name. For example, the atoi() function in the string
module is called [Link]().
Each module defines its own unique namespace. If we created a function called atoi() in our own
module, perhaps mymodule, its name would be [Link]().
SEARCH PATH AND PATH SEARCH
The process of importing a module requires a process called a path search. This is the procedure of
checking "predefined areas" of the file system to look for our [Link] file in order to load the
mymodule module.
These predefined areas are no more than a set of directories that are part of our Python search path. To
avoid the confusion between the two, think of a path search as the pursuit of a file through a set of
directories, the search path.
A default search path is automatically defined either in the compilation or installation process. This
search path may be modified in one of two places.
1. Environment Variables: You can set environment variables that affect the search paths used
during compilation and linking.
2. Compilation and Installation Options: When configuring and building software, you can often
specify custom search paths using options during the compilation and installation process
MODULE BUILT-IN FUNCTIONS
11. DISCUSS ABOUT MODULE BUILT-IN FUNCTIONS. (PART-B/C)
1. import ()
The purpose of this function is to allow for overriding it if the user is inclined to develop our own
importation algorithm.
The syntax of import () is:
import (module_name[, globals[, locals[, fromlist]]])
The module_name variable is the name of the module to import, globals is the dictionary of current
names in the global symbol table, locals is the dictionary of current names in the local symbol table, and
fromlist is a list of symbols to import the way they would be imported using the from-import statement.
The globals, locals, and fromlist arguments are optional, and if not provided, default to globals(),
locals(), and [], respectively.
Calling import sys can be accomplished with
sys = import ('sys')
2. globals() and locals()
The globals() and locals() built-in functions return dictionaries of the global and local namespaces,
respectively, of the caller.
From within a function, the local namespace represents all names defined for execution of that function,
which is what locals() will return.
From the global namespace, however, globals() and locals() return the same dictionary because the
global namespace is as local as you can get while executing there.
Here is a little snippet of code that calls both functions from both namespaces:
def add(x,y):
z=x+y
print ('global symbol table:', globals())
print ('local symbol table:', locals())
return z
To run the above program we can get the below output:

61

Downloaded by priya loganathan (priyacs104@[Link])


>>>add(5,5)
global symbol table: {' name ': ' main ', ' doc ': None, ' package ': None, ' loader ':
<class '_frozen_importlib.BuiltinImporter'>, ' spec ': None, ' annotations ': {}, ' builtins ':
<module 'builtins' (built-in)>, ' file ':
'C:/Users/cs_pm.STAFF/AppData/Local/Programs/Python/Python312/[Link]', 'add': <function add at
0x0000026BFBDA09A0>}
local symbol table: {'x': 5, 'y': 5, 'z': 10}
10
3. reload()
The reload() built-in function performs another import on a previously imported module.
The syntax of reload() is:
o reload(module) - module is the actual module we want to reload.
There are some criteria for using the reload() module.
1. The first is that the module must have been imported in full (not by using from-import), and it must
have loaded successfully.
2. The second rule follows from the first, and that is the argument to reload() the module itself and not a
string containing the module name, i.e., it must be something like reload (sys) instead of
reload('sys').
CLASSES
12. EXPLAIN THE CONCEPT OF CLASSES IN PYTHON. (PART-B)
A class is a data structure that we can use to define objects that hold together data values and behavioral
characteristics.
Classes are entities that are the programmatic form of an abstraction for a real-world problem, and
instances are realizations of such objects.
One analogy is to liken classes to blueprints or molds with which to make real objects (instances).
In Python, class declarations are very similar to function declarations, a header line with the appropriate
keyword followed by a suite as its definition, as indicated below:
class ClassName(object):
'class documentation string'
class_suite
CREATING CLASSES
Python classes are created using the class keyword. In the simple form of class declarations, the name of
the class immediately follows the keyword:
class ClassName(bases):
'class documentation string'
class_suite
bases is the set of one or more parent classes from which to derive; and class_suite consists of all the
component statements, defining class members, data attributes, and functions.
Classes are generally defined at the top-level of a module so that instances of a class can be created
anywhere in a piece of source code where the class is defined.
DECLARATION VERSUS DEFINITION
As with Python functions, there is no distinction between declaring and defining classes because they
occur simultaneously, i.e., the definition (the class suite) immediately follows the declaration (header
line with the class keyword) and the always recommended, but optional, documentation string.
CLASS ATTRIBUTES
13. DESCRIBE ABOUT CLASS ATTRIBUTES. (PART-B)
An attribute is a data or functional element that belongs to another object and is accessed via the familiar
dotted-attribute notation. Some Python types such as complex numbers have data attributes (real and
imag), while others such as lists and dictionaries have methods (functional attributes).
Some familiar examples are:
o [Link]('foo')
o print([Link]. doc )
o [Link](map(upper, open('x').readlines()))
Class data attributes are useful only when a more "static" data type is required.

62

Downloaded by priya loganathan (priyacs104@[Link])


CLASS DATA ATTRIBUTES
Data attributes are simply variables of the class we are defining. They can be used like any other variable
in that they are set when the class is created and can be updated either by methods within the class or
elsewhere in the main part of the program.
Such attributes are better known to OO programmers as static members, class variables, or static data.
They represent data that is tied to the class object they belong to and are independent of any class
instances.
Static members are generally used only to track values associated with classes.
Here is an example of using a class data attribute (foo):
>>> class c(object):
... foo = 100
>>> print([Link])
100
>>> [Link] = [Link] + 1
>>> print([Link])
101
METHODS
We can also define a function inside a Python class. A Python function defined inside a class is called
a method. For example:
# create a class
class Room:
length = 0.0
breadth = 0.0

# method to calculate area


def calculate_area(self):
print("Area of Room =", [Link] * [Link])

# create object of Room class


study_room = Room()

# assign values to all the properties


study_room.length = 42.5
study_room.breadth = 30.8

# access method inside class


study_room.calculate_area()
To run the above program we can get the below output:
Area of Room = 1309.0
Binding (Bound and Unbound Methods)
If a function is an attribute of class and it is accessed via the instances, they are called bound methods.
A bound method is one that has ‘self‘ as its first argument. Since these are dependent on the instance
of classes, these are also known as instance methods.
Methods that do not have an instance of the class as the first argument are known as unbound methods.
DETERMINING CLASS ATTRIBUTES
There are two ways to determine what attributes a class has. The simplest way is to use the dir() builtin
function. An alternative is to access the class dictionary attribute dict , one of a number of special
attributes that is common to all classes.
For example, using the class defined above, let us use dir() and the special class attribute dict to see
this class's attributes:
>>> dir(Room)
[' class ', ' delattr ', ' dict ', ' dir ', ' doc ', ' eq ', ' format ', ' ge ',
' getattribute ', ' getstate ', ' gt ', ' hash ', ' init ', ' init_subclass ', ' le ',

63

Downloaded by priya loganathan (priyacs104@[Link])


' lt ', ' module ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ',
' sizeof ', ' str ', ' subclasshook ', ' weakref ', 'breadth', 'calculate_area', 'length']
>>> print(Room. dict )
{' module ': ' main ', 'length': 0.0, 'breadth': 0.0, 'calculate_area': <function
Room.calculate_area at 0x00000238BB3B0900>, ' dict ': <attribute ' dict ' of 'Room'
objects>, ' weakref ': <attribute ' weakref ' of 'Room' objects>, ' doc ': None}
SPECIAL CLASS ATTRIBUTES
Special Class Attributes
Attributes Meanings
Room. name String name of class Room.
Room. doc Documentation string for class Room.
Room. bases Tuple of class Room 's parent classes.
Room. dict Attributes of Room.
Room. module Module where Room is defined.
Room. class Class of which Room is an instance.
Using the class MyClass we just defined above, we have the following:
>>> Room. name
'Room'
>>> Room. bases
(<class 'object'>,)
>>> Room. module
' main '
>>> Room. class
<class 'type'>
INSTANCES
14. DISCUSS IN DETAIL ABOUT INSTANCES. (PART-B)
Whereas a class is a data structure definition type, an instance is a declaration of a variable of that type.
In other words, instances are classes brought to life.
Instances are the objects that are used primarily during execution, and the types of all instances are the
class from which they were instantiated.
INSTANTIATION: CREATING INSTANCES BY INVOKING CLASS OBJECT
Once a class has been defined, creating an instance is no more difficult than calling a functionliterally.
Instantiation is realized with use of the function operator, as in the following example:
>>>class Myclass(object):
…pass
>>>obj=Myclass()
Creating instance obj of class Myclass consists of "calling" the class: Myclass().
INIT () "CONSTRUCTOR" METHOD
When the class is invoked, the first step in the instantiation process is to create the instance object. Once
the object is available, Python checks if an init () method has been implemented.
By default, no special actions are enacted on the instance without the definition of (or the overriding) of
the special method init ().
If init () has not been implemented, the object is then returned and the instantiation process is
complete.
In summary,
(a) We don’t call new to create an instance, and we don’t define a constructor: Python creates the object.
(b) init (), is simply the first method that is called after the interpreter creates an instance.
init () is one of many special methods that can be defined for classes. Some of these special methods
are predefined with inaction as their default behavior, such as init (), and must be overridden for
customization while others should be implemented on an as-needed basis.
NEW () "CONSTRUCTOR" METHOD
The new () special method bears a much closer resemblance to a real constructor than init ().
The reason why we say that new () is more like a constructor than init () is that it has to return a

64

Downloaded by priya loganathan (priyacs104@[Link])


valid instance so that the interpreter can then call init () with that instance as self.
Calling a superclass new () to create the object is just like using a new keyword to create an object.
new () and init () are both passed the (same) arguments as in the class creation call.
DEL () "DESTRUCTOR" METHOD
Destructors in Python are methods that provide special processing before instances are deallocated and
are not commonly implemented since instances are seldom deallocated explicitly.
If you do override del (), be sure to call any parent class del () first so those pieces can be
adequately deallocated.
Example
The final step is to remove all the aliases by using the del statement and discovering when and how
many times the destructor is called.
>>>class c(): # class declaration
def init (self): # "constructor"
print('Initialized')
def del (self): # "destructor"
print('Deleted')

>>>c1=c() # instantiation
Initialized
>>>c2=c1 # create additional alias
>>>c3=c1
>>>id(c1)
2442682648240
>>>del c1
>>>del c2
>>>del c3 # remove final reference
Deleted # destructor finally invoked
In the above example, the destructor was not called until all references to the instance of class C were
removed, e.g., when the reference count has decreased to zero.
The destructor is called exactly once, the first time the reference count goes to zero and the object
deallocated. This makes sense because any object in the system is allocated and deallocated only once.
REFERENCE BOOK:
1. Wesley J. Chun, "Core Python Programming", Pearson Education Publication, 2012.
2. [Link]
3. [Link]
4. [Link]
IMPORTANT / POSSIBLE QUESTIONS
PART-A (1 MARK)
CHOOSE THE CORRECT ANSWER:
1. Which keyword is used for function?
a) Fun b) Define c) def d) Function
2. Which are the advantages of functions in python?
a) Reducing duplication of code b) Decomposing complex problems into simpler pieces
c) Improving clarity of the code d) All of the mentioned
3. Where is function defined?
a) Module b) Class c) Another function d) All of the mentioned
4. What is called when a function is defined inside a class?
a) Module b) Class c) Another function d) Method
5. Python supports the creation of anonymous functions at runtime, using a construct called .
a) lambda b) pi c) anonymous d) none of the mentioned
6. What will be the output of the following Python code?
y=6
z = lambda x: x * y
print z(8)
65

Downloaded by priya loganathan (priyacs104@[Link])


a) 48 b) 14 c) 64 d) None of the mentioned

7. What will be the output of the following Python code?


import functools
l=[1,2,3,4]
print([Link](lambda x,y:x*y,l))
a) Error b) 10 c) 24 d) No output
8. Which of the following numbers will not be a part of the output list of the following Python code?
def sf(a):
return a%3!=0 and a%5!=0
m=filter(sf, range(1, 31))
print(list(m))
a) 1 b) 29 c) 6 d) 10
9. The symbol along with the name of the decorator function can be placed above the
definition of the function to be decorated works as an alternate way for decorating a function.
a) # b) $ c) @ d) &
10. Which of these definitions correctly describes a module?
a) Denoted by triple quotes for providing the specification of certain program elements
b) Design and implementation of specific functionality to be incorporated into a program
c) Defines the specification of how it is to be used
d) Any program that reuses code
11. Program code making use of a given module is called a of the module.
a) Client b) Docstring c) Interface d) Modularity
12. is a string literal denoted by triple quotes for providing the specifications of certain
program elements.
a) Interface b) Modularity c) Client d) Docstring
13. Which of the following is not a valid namespace?
a) Global namespace b) Public namespace
c) Built-in namespace d) Local namespace
14. represents an entity in the real world with its identity and behaviour.
a) A method b) An object c) A class d) An operator
15. is used to create an object.
a) class b) constructor c) User-defined functions d) In-built functions
16. All classes have a function called?
a) init b) init () c) C. init d) init()
17. A variable that is defined inside a method and belongs only to the current instance of a class is
known as?
a) Inheritance b) Instance variable
c) Function overloading d) Instantiation
PART-B (5 MARKS)
1. Explain about Functions. (Refer [Link], [Link])
2. How to Create a Function? (Refer [Link], [Link])
3. Comment on def statement. (Refer [Link], [Link])
4. How do you pass arguments into a Function in Python? (Refer [Link], [Link])
5. Comment on Filter( ). (Refer [Link], [Link])
6. Define Map( ). (Refer [Link] [Link])
7. Comment on Reduce( ). (Refer [Link], [Link])
8. Explain about Modules and Files. (Refer [Link], [Link])
9. Describe about Class Attributes. (Refer [Link], [Link])
11. Discuss in detail about Instances. (Refer [Link], [Link])
PART-C (10 MARKS)
1. How do you call a Function? (Refer [Link], [Link])
2. Discuss about Modules. (Refer [Link], [Link])
3. Discuss about Module Built-In Functions. (Refer [Link], [Link])
4. Explain the concept of Classes in Python. (Refer [Link], [Link])
66

Downloaded by priya loganathan (priyacs104@[Link])

You might also like