13 Introduction To Python Function and Classes

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 15

Selenium Webdriver Training -

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;

def : keyword for declaring


def function_name(parameters): functions
function_name: name of the
"""docstring""" function
parameters: the input provided
statement(s) to function

docsting is used to explain


in brief, what a function
does.

Declaration of main logic of


function including return
statement
Function example
def greeting(name):
“““
This function is been develop
to greet the person with name
provided in input parameters
note: input tupe should be string
e.g. greeting('maryam')
”””

print ("Have a nice day %s !" % name)


Operations On Functions
 Code in the function would be executed once it is been called, in python function could be call simply by calling the function name with
required arguments.
E.g. in previous example function would be call like;
greeting('maryam')
 All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function,
the change also reflects back in the calling function. E.g.

def name_func(name): # defining the function taking string as an argument


name += 'abc‘ # extend the name with ‘abc’ string
print ("The entered name is: ", name)
return name
n = 'maryam‘ # declaring the value of the name
n = name_func(n) # calling the function and assigning return statement value to same variable again
The entered name is: maryamabc # print statement in the function would be print during execution of code
Operations On Functions

 Default parameters would be provided in the function declaration. e.g.

>>> def test(a = 1):


b=1
print ("Provided arg is %d and sum is %d" %(a, a+b))

>>> 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;

 If user inputs negative number, function should return warning message


 If user inputs ‘0’, function should return value = 1
 If
user enters any value greater than zero then function should computes its factorial
def fact(n):
factorial = 1
if n < 0:
return 'N/A'
elif n == 0:
return 1
else:
for i in range(1, n+1):
factorial = factorial * i
return factorial
Python - Class

 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

def __init__(self, name):


“““
Many classes like to create objects with instances customized to a specific initial state.
Therefore a class may define a special method named __init__()
”””

self.name = name # instance variable unique to each instance

>>> 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

The four major principles of object orientation are:


 Inheritance
 Encapsulation
 Polymorphism
Python – OOP - Inheritance

class Polygon: def __init__(self):


def __init__(self, no_of_sides): Polygon.__init__(self,3)
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)] def findArea(self):
a, b, c = self.sides
def inputSides(self): # calculate the semi-perimeter
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in s = (a + b + c) / 2
range(self.n)]
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
def dispSides(self):
for i in range(self.n):
new = Triangle()
print("Side",i+1,"is",self.sides[i])
new.inputSides()
new.findArea()
class Triangle(Polygon):
new.dispSides()
Python – OOP – Encapsulation

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

 Polymorphic behavior allows you to print ("Woof woof!")


specify common methods in an "abstract"
def makeSound(animalType):
level, and implement them in particular
instances. For your example: animalType.sound()

class Bear(object): bearObj = Bear()


def sound(self): dogObj = Dog()
print ("Groarrr")
class Dog(object): makeSound(bearObj)
def sound(self): makeSound(dogObj)

You might also like