13 Introduction To Python Function and Classes
13 Introduction To Python Function and Classes
13 Introduction To Python Function and Classes
Python
INTRODUCTION TO PYTHON – FUNCTIONS & CLASSES
PRESENTED BY: ENGR.SUMREENA BANO
Python - Functions
Function provides block of re-usable code, which can be called wherever required within an application.
When application grows with time, functions help to provide manageable code.
Syntax of function is as follows;
>>> test(5)
Provided arg is 5 and sum is 6
>>> test()
Provided arg is 1 and sum is 2
Lambda Functions
One liner definition and declaration would be covered in lambda function e.g. following
is an example for simple lambda function to calculate square of provided parameter;
>>> d = lambda p: p * 2
>>> x = d(2)
>>> x
4
Other simple example is;
Assignment
1. Write a function which takes an input and calculate its factorial; there are following three conditions;
A class is a kind of data type, just like a string, integer or list. When we create an object
of that data type, we call it an instance of a class.
Like any other language Python classes provide all the standard features of Object
Oriented Programming:
The class inheritance mechanism allows multiple base classes
A derived class can override any methods of its base class or classes
A method can call the method of a base class with the same name
Python - Class
class Dog:
kind = 'canine' # class variable shared by all instances
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
Assignment
Create a new class book, add a variable of year and assign value to variable, add a
function in class which takes author name as an input. Simply print the name of the
author in function.
Make an instance of the class and call the function
>>> class Book:
year = 2015
def __init__(self, name):
self.name = name
def func(self):
print (“Author name is: ", self.name)
>>> b = Book('Spider')
>>> b.func()
Book name is: Spider
Python - OOP
class C(object):
Type Description def __init__(self):
self.a = 123 # OK to access directly
public self._a = 123 # should be considered private
Accessible from anywhere
methods self.__a = 123 # considered private, name mangled
private Accessible only in their own class. starts with two >>> c = C()
methods underscores >>> c.a
123
public >>> c._a
Accessible from anywhere 123
variables
>>> c.__a
Traceback (most recent call last):
private Accessible only in their own class or by a method if File "<stdin>", line 1, in <module>
variables defined. starts with two underscores AttributeError: 'C' object has no attribute '__a'
>>> c._C__a
123
Python – OOP – Encapsulation
class Car:
__maxspeed = 0 def setMaxSpeed(self,speed):
__name = "" self.__maxspeed = speed
def __init__(self):
self.__maxspeed = 200 redcar = Car()
self.__name = "Supercar" redcar.drive()
redcar.setMaxSpeed(320)
def drive(self): redcar.drive()
print ("driving.maxspeed: " + redcar._Car__name
str(self.__maxspeed))
Python - OOP – Polymorphism