Sei sulla pagina 1di 55

Unit - II:

Developing
Internet of
Things
Dr. Lakshmi. S
Associate Professor,
ECE, RIT, Bangalore
IoT Platforms Design Methodology
 IoT systems comprise of multiple components,
deployment levels and configurations etc
based on the application
 The design process of an IoT system has to
consider – interactions between various
components / devices, network resources,
web services, components like analytics,
applications and DB services
 As there are wide choices available for the
components etc, the design process of an IoT
system is both challenging and complex
 A design done considering a specific product
/ service would lead to a product or service or
vendor lock-in whereby complicating system
upgrades, maintenance etc for the customer
IoT System Design Methodology – Steps (1 of 2)
Purpose and Requirements
Define the purpose, behavior and Requirements (like Management, Data analysis)of
the IoT system

Process Model Specification


Define the use cases

Domain Model Specification


Define Physical Entities, Virtual Entities, Devices, Resources and Services in the IoT
System

Information Model Specifications


Define the structure (eg., relations, attributes) of all the information in the IoT
system

Service Specifications
Map Process and Information models to services and define service
specifications

A
IoT System Design Methodology – Steps (2 of 2)
A

IoT Level Specifications


Define the IoT level for the system

Functional View Specification


Map IoT level to functional groups

Operational View Specification


Define Communication Options, Service hosting options, storage options,
device options

Device and Component Integration


Integrate devices, develop and integrate components

Application Development
Develop Applications
IOT Design Methodology
Ex: Designing a Smart Home Automation System!!

1. The Purpose and Requirements


a. Purpose: An automation systems that allows controlling of the
lights in a home remotely using a web application
b. Behavior: Should have auto (measures the light level in a room
and switches on the light when it is dark) / manual (option to
manually and remotely turn on the light in a room) modes
c. System management requirement: The system should provide
remote monitoring and control functions
d. Data analysis requirement: the system should perform local
analysis of the data
e. Application development requirement: The application should
be deployed locally on the device, but should be accessible
remotely
2. Process Specification
a. When the system is in auto mode, it should monitor the brightness
inside the room continuously and turn on the light if the
brightness is low and off the light when the brightness is high
b. When in manual mode the system checks the light state set by
the user and accordingly turn ON / OFF the light
Designing a Smart Home Automation
System!!

Mode

auto manua
l

Light- Light-
Level State
Level: State: State:
Level:
High On Off
Low

State: On State: Off State: On State: Off


3. Domain Mode Specifications: (main concept, entities
and objects)
a. Physical Entity: Discrete and identifiable environmental
entities like room switch for the light, an appliance etc., and,
the particular sensor
b. Virtual Entity: For each physical entity there is a
corresponding virtual entity for the digital world - like for
monitoring of the room, controlling an appliance
c. Device: medium between the physical and virtual entities;
like, gather information from the physical entity (like from the
sensors) and perform actions such as actuation with tags
such as LDR1, SW1 etc
d. Resource: SW components on-device (like the OS) or
network resource (like the DB)
e. Service: interface for interacting with the physical entity (like
the thread that monitors the light conditions)
4. 4.Information Model: A virtual entity for each - light
state and light level
5. Service Specifications: Service - type, inputs / outputs,
5.schedule etc. Eg., GET (current mode) / PUT (turn
on/off) requests
6. IoT Level Specification: Specification of
deployment level, which is 1 in the case of Home
Automation
7. Functional View Specification: like Functional
Groups (FG) for the device(minicomputer, sensor
and actuator), communication (IPv6+TCP + HTTP),
services(device monitoring, device discovery,
Security and application
8. Operational Specifications: like which API for
communication, which protocol (like TCP, HTTP),
services, MySql for DB etc
9. Device and Component Integration: Schematic of
the single-board computer platform for integration,
specifications of the LDR sensor etc
10. Application Development: Design the screen shots,
mock UI flows etc
Motivation to use Python
 Python language employs intuitive key-words,
simpler syntax – so easy to learn
 Python code is compact
 Python is supported on wider range of platforms –
so code is portable
 Wide library support
 Meets the end-to-end development needs of IoT
systems – for capturing sensor data, web services,
web applications, analytical components
Python
 Python is a general-purpose high level programming
language and suitable for providing a solid foundation to
the reader in the area of cloud computing.

 The main characteristics of Python are:


 Multi-paradigm programming language
Python supports more than one programming paradigms
including object-oriented programming and structured
programming
 Interpreted Language
 Python is an interpreted language and does not
require an explicit compilation step. The Python
interpreter executes the program source code directly,
statement by statement, as a processor or scripting
engine does.
 Interactive Language
 Python provides an interactive mode in which the user
can submit commands at the Python prompt and
interact with the interpreter directly.
Python - Benefits
 Easy-to-learn, read and maintain
 Python is a minimalistic language with relatively few keywords, uses English
keywords and has fewer syntactical constructions as compared to other
languages. Reading Python programs feels like English with pseudo-code like
constructs. Python is easy to learn yet an extremely powerful language for a wide
range of applications.
 Object and Procedure Oriented
 Python supports both procedure-oriented programming and object-oriented
programming. Procedure oriented paradigm allows programs to be written around
procedures or functions that allow reuse of code. Procedure oriented paradigm
allows programs to be written around objects that include both data and
functionality.
 Extendable
 Python is an extendable language and allows integration of low-level modules
written in languages such as C/C++. This is useful when you want to speed up a
critical portion of a program.
 Scalable
 Due to the minimalistic nature of Python, it provides a manageable structure for
large programs.
 Portable
 Since Python is an interpreted language, programmers do not have to worry about
compilation, linking and loading of programs. Python programs can be directly
executed from source
 Broad Library Support
 Python has a broad library support and works on various platforms such as
Windows, Linux, Mac, etc.
Python - Setup
 Windows
 Python binaries for Windows can be downloaded from
http://www.python.org/getit .
 For the examples and exercise in this book, you would require Python 2.7
which can be directly downloaded from:
http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi
 Once the python binary is installed you can run the python shell at the
command prompt using
> python

 Linux
#Install Dependencies
sudo apt-get install build-essential
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev
libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev

#Download Python
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar -xvf Python-2.7.5.tgz
cd Python-2.7.5

#Install Python
./configure
make
sudo make install
Numbers
 Numbers
 Number data type is used to store numeric values. Numbers are immutable data
types, therefore changing the value of a number data type results in a newly
allocated object.

#Integer
>>>a=5 #Addition #Division
>>>type(a) >>>c=a+b >>>f=b/a
<type ’int’> >>>c >>>f
#Floating Point 7.5 0.5
>>>b=2.5 >>>type(c) >>>type(f)
>>>type(b) <type ’float’> <type float’>
<type ’float’>
#Long #Subtraction #Power
>>>x=9898878787676L >>>d=a-b >>>g=a**2
>>>type(x) >>>d >>>g
<type ’long’> 2.5 25
#Complex >>>type(d)
>>>y=2+5j <type ’float’>
>>>y
(2+5j) #Multiplication
>>>type(y) >>>e=a*b
<type ’complex’> >>>e
>>>y.real 12.5
2 >>>type(e)
>>>y.imag <type ’float’>
5
Strings
 Strings
 A string is simply a list of characters in order. There are no limits to the number of
characters you can have in a string.

#Printstring
#Create string
>>>print s
#strip: Returns a copy
>>>s="Hello World!" of the string with the
Hello World!
>>>type(s)
#leading and trailing
<type ’str’>
#Formatting output characters removed.
>>>print "The string (The
#String concatenation
string (Hello World!) has >>>s.strip("!")
>>>t="This is sample
12 characters
program." ’Hello World’
>>>r = s+t
#Convert to upper/lower
>>>r
case
’Hello World!This is sample
>>>s.upper()
program.’
’HELLO WORLD!’
>>>s.lower()
#Get length of string
’hello world!’
>>>len(s)
12
#Accessing sub-strings
>>>s[0]
#Convert string to integer
’H’
>>>x="100"
>>>s[6:]
>>>type(s)
’World!’
<type ’str’>
>>>s[6:-1]
>>>y=int(x)
’World’
>>>y
100
Lists
List a compound data type used to group together other values. List items need not
all have the same type. A list contains items separated by commas and enclosed
within square brackets.

#Create List Python program to # Python program to


# Python program to demonstrate demonstrate
# Addition of elements in a List
demonstrate # Addition of elements in a List
# Creation of List # Creating a List
List = [] # Creating a List
# Creating a List print("Initial blank List: ") List = [1,2,3,4]
List = [] print(List) print("Initial List: ")
print("Intial blank List: ") print(List)
print(List) # Addition of Elements
# in the List
# Addition of Element at
List.append(1)
# Creating a List with List.append(2) # specific Position
# the use of a String List.append(4) # (using Insert Method)
List = ['GeeksForGeeks'] print("\nList after Addition of List.insert(3, 12)
print("\nList with the use of Three elements: ") List.insert(0, 'Geeks')
String: ") print(List) print("\nList after performing
print(List) Insert Operation: ")
# Adding elements to the List
print(List)
# using Iterator
>>>List = [1, 2, 4, 4, 3, 3, 3, 6, for i in range(1, 4): nitial List: [1, 2, 3, 4] List after
5] List.append(i) performing Insert Operation:
print("\nList with the use of print("\nList after Addition of ['Geeks', 1, 2, 3, 12, 4]
Numbers: ") elements from 1-3: ")
print(List) print(List)
Intial blank List: [] Initial blank List: []
List after Addition of Three
List with the use of String:
elements: [1, 2, 4]
['GeeksForGeeks'] List after Addition of elements
List with the use of Numbers: from 1-3: [1, 2, 4, 1, 2, 3]
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Tuples
 A tuple is a sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas and enclosed within parentheses. Unlike
lists, the elements of tuples cannot be changed, so tuples can be thought of as
read-only lists.

#Create a Tuple #Get an element from a tuple


>>>fruits=("apple","mango","ban >>>fruits[0]
ana","pineapple") ’apple’
>>>fruits >>>fruits[:2]
(’apple’, ’mango’, ’banana’, (’apple’, ’mango’)
’pineapple’)
#Combining tuples
>>>type(fruits) >>>vegetables=(’potato’,’carrot’,’o
<type ’tuple’> nion’,’radish’)
>>>eatables=fruits+vegetables
#Get length of tuple >>>eatables
>>>len(fruits) (’apple’, ’mango’, ’banana’,
4 ’pineapple’, ’potato’, ’carrot’,
’onion’, ’radish’)
Dictionaries
 Dictionaries
 Dictionary is a mapping data type or a kind of hash table that maps keys to values.
Keys in a dictionary can be of any data type, though numbers and strings are
commonly used for keys. Values in a dictionary can be any data type or object.

#Create a dictionary
>>>student={’name’:’Mary’
#Get all keys in a dictionary #Check if dictionary has
>>>student.keys() a key
,’id’:’8776’,’major’:’CS’} [’gender’, ’major’, ’name’,
>>>student >>>student.has_key(’na
’id’]
{’major’: ’CS’, ’name’: #Get all values in a me’)
’Mary’, ’id’: ’8776’} True
dictionary
>>>type(student) >>>student.has_key(’gr
>>>student.values()
<type ’dict’> [’female’, ’CS’, ’Mary’, ade’)
’8776’] False
#Get length of a dictionary #Add new key-value pair
>>>len(student) >>>student[’gender’]=’fema
3 le’
>>>student
#Get the value of a key in {’gender’: ’female’, ’major’:
dictionary ’CS’, ’name’: ’Mary’, ’id’:
>>>student[’name’] ’8776’}
’Mary’
#A value in a dictionary can
be another dictionary
#Get all items in a >>>student1={’name’:’David
dictionary ’,’id’:’9876’,’major’:’ECE’}
>>>student.items() >>>students={’1’:
[(’gender’, ’female’), student,’2’:student1}
(’major’, ’CS’), (’name’, >>>students
’Mary’), (’id’, ’8776’)] {’1’: {’gender’: ’female’,
Type Conversions
 Type conversion examples

#Convert to string #Convertto long


>>>a=10000 >>>long(b)
>>>str(a) 2013L
’10000’
#Convert to list
#Convert to int >>>s="aeiou"
>>>b="2013" >>>list(s)
>>>int(b) [’a’, ’e’, ’i’, ’o’, ’u’]
2013
#Convert to set
#Convert to float >>>x=[’mango’,’apple’,’bana
>>>float(b) na’,’mango’,’banana’]
2013.0 >>>set(x)
set([’mango’, ’apple’,
’banana’])
Control Flow – if statement
 The if statement in Python is similar to the if statement in other
languages.
>>>a = 25**5 >>>if a>10000: >>>student={’name’:
>>>if a>10000: if >>>s="Hello World" ’Mary’,’id’:’8776’}
a<1000000: >>>if "World" in s: >>>if not
print s=s+"!" student.has_key(’maj
"More" print print s or’):
else: "Between 10k and 100k" student[’
else: Hello World! major’]=’CS’
print
"Less" print "More >>>student
than 100k" {’major’: ’CS’,
elif ’name’: ’Mary’, ’id’:
More a==10000: ’8776’}
print "Equal
to 10k"
else:

print "Less
than 10k"

More than 100k


Control Flow – for statement
 The for statement in Python iterates over items of any sequence
(list, string, etc.) in the order in which they appear in the sequence.
 This behavior is different from the for statement in other languages
such as C in which an initialization, incrementing and stopping
criteria are provided.
#Looping over #Looping over items in #Looping over keys in
characters in a a list a dictionary
string
fruits=[’apple’,’orange student = ’name’:
helloString = "Hello ’,’banana’,’mango’] ’Mary’, ’id’:
World" ’8776’,’gender’:
i=0 ’female’, ’major’: ’CS’
for c in helloString: for item in fruits:
print c print "Fruit- for key in student:
%d: %s" % (i,item) print "%s: %s"
H i=i+1 % (key,student[key]
E
L
L
0

W
O
R
Control Flow – while statement
 The while statement in Python executes the statements within the
while loop as long as the while condition is true.

#Prints even numbers upto


100

>>> i = 0

>>> while i<=100:


if i%2 == 0:
print i
i = i+1
Control Flow – range statement

 The range statement in Python generates a list of numbers in


arithmetic progression.

#Generate a list of numbers #Generate a list of numbers


from 0 – 9 from 10 - 100 with increments
of 10
>>>range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>range(10,110,10)
[10, 20, 30, 40, 50, 60, 70, 80,
90,100]
Control Flow – break/continue statements

 The break and continue statements in Python are similar to the


statements in C.
#Break statement
 Break example
 Break statement breaks out of the for/while loop >>>y=1
>>>for x in range(4,256,4):
y=y*x
if y > 512:

break
print y
4
 Continue 32
384
 Continue statement continues with the next iteration.

#Continue statement example


>>>fruits=[’apple’,’orange’,’banana’,
’mango’]
>>>for item in fruits:
if item == "banana":
continue
else:
print item

apple
orange
Control Flow – pass statement
 The pass statement in Python is a null operation.
 The pass statement is used when a statement is required
syntactically but you do not want any command or code to
execute.
>fruits=[’apple’,’orange’,’banana’
,’mango’]
>for item in fruits:
if item == "banana":
pass
else:
print item

apple
orange
mango
Write the program that prompts the user for a list of numbers and prints out the maximum and
minimum of the numbers at the end when the user enters “done”. Write the program to store
the numbers the user enters in a list and use the max() and min() functions to compute the
maximum and minimum numbers after the loop completes

numlist = list()
while ( True ) :
inp = input('Enter a number: ')
if inp == 'done' :
break
value = float(inp)
numlist.append(value)
print(numlist)
print(max(numlist))
print(min(numlist))
Functions
 A function is a block of code that takes
information in (in the form of parameters), students = { '1': {'name': 'Bob', 'grade': 2.5},
does some computation, and returns a '2': {'name': 'Mary', 'grade': 3.5},
new piece of information based on the '3': {'name': 'David', 'grade':
parameter information. 4.2},
 A function in Python is a block of code '4': {'name': 'John', 'grade': 4.1},
that begins with the keyword def '5': {'name': 'Alex', 'grade': 3.8}}
followed by the function name and
parentheses. The function parameters
are enclosed within the parenthesis. def averageGrade(students):
 The code block within a function begins ‘’’This function computes the average
after a colon that comes after the grade’’’
parenthesis enclosing the parameters. sum = 0.0
 The first statement of the function body for key in students:
can optionally be a documentation sum = sum + students[key]['grade']
string or docstring. average = sum/len(students)
return average
Syntax
avg = averageGrade(students)
def functionname( print ("The average grade is: %0.2f" % (avg))
parameters ):
“’function_docstring“’
function_suite
return [expression]
Functions - Default Arguments
 Functions can have default values of the parameters.
 If a function with default values is called with fewer parameters or without
any parameter, the default values of the parameters are used

def printinfo( name, age = 35 ):


"This prints a passed info into this
function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo(name = "miki" , age = 50)
printinfo( name = "miki" )

Output
Name: miki
Age 50

Name: miki
Age 35
Functions - Passing by Reference
 All parameters in the Python functions are passed by reference.
 If a parameter is changed within a function the change also reflected
back in the calling function.
# Function definition is here def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ",mylist)

mylist[2]=50
print ("Values inside the function after change: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Output
Values inside the function before change: [10, 20,
30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
Functions - Passing by Reference

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]
# This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)

Output
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Functions - Keyword Arguments
 Functions can also be called using keyword arguments that identifies the
arguments by the parameter name when the function is called.
 This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters
def #Correct use
printStudentRecords(name,age=20,major=’C printStudentRecords(name=’Alex’)
S’): Name: Alex
print( "Name: " , name) Age: 20
print ("Age: " , age) Major: CS
print ("Major: “ , major)
printStudentRecords(name=’Bob’,age=22,major
#This will give error as name is required =’ECE’)
argument Name: Bob
printStudentRecords() Age: 22
Major: ECE
Output
Traceback (most recent call last): printStudentRecords(name=’Alan’,major=’ECE’)
File "<stdin>", line 1, in <module> Name: Alan
TypeError: printStudentRecords() takes at Age: 20
least 1 argument (0 given) Major: ECE
Functions - Variable Length Arguments
 Python functions can have variable length arguments. The variable length
arguments are passed to as a tuple to the function with an argument
prefixed with asterix (*)
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed
arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

Output is: 10
Output is: 70 60 50
Modules #Using student module
>>>import student
#student module - saved as student.py
def averageGrade(students): >>>students =
 Python allows sum = 0.0 '1': 'name': 'Bob', 'grade': 2.5,
organizing the for key in students: '2': 'name': 'Mary', 'grade': 3.5,
'3': 'name': 'David', 'grade': 4.2,
program code into sum = sum +
students[key]['grade'] '4': 'name': 'John', 'grade': 4.1,
different modules average = sum/len(students) '5': 'name': 'Alex', 'grade': 3.8
which improves the return average
>>>student.printRecords(students)
code readability and
def printRecords(students): There are 5 students
management. Print( "There are %d students“ Student-1:
 Consider a module %(len(students))) Name: Bob
i=1 Grade: 2.5
to be the same as a for key in students: Student-2:
code library. A file print( "Student-%d: " % (i)) Name: David
containing a set of print ("Name: " Grade: 4.2
,students[key]['name']) Student-3:
functions you want to print "Grade: " Name: Mary
include in your ,str(students[key]['grade']) Grade: 3.5
application. i = i+1 Student-4:
Name: Alex
 Modules can be # Importing a specific function Grade: 3.8
from a module Student-5:
imported using the >from student import Name: John
import keyword. averageGrade Grade: 4.1
 Modules to be # Listing all names defined in a >>>avg = student.
imported must be module averageGrade(students)
present in the search >>>dir(student) >>>print ("The average grade is:
path. %0.2f" % (avg))
3.62
File Handling
 In Python, a file is categorized as either text or
binary, and the difference between the two file
types is important.
 Text files are structured as a sequence of lines,
where each line includes a sequence of
characters. This is what you know as code or
syntax.
 Each line is terminated with a special character,
called the EOL or End of Line character. There are
several types, but the most common is the comma
{,} or newline character. It ends the current line
and tells the interpreter a new one has begun.
File generation
Create a text file


 file =
To get more familiar with text files in
Python, let’s create our own and do
open(“testfile.txt”,”w”)
some additional exercises.
 Using a simple text editor, let’s  file.write(“Hello World”)
create a file. You can name it
anything you like, and it’s better to  file.write(“This is our new

use something you’ll identify with.
For the purpose of this tutorial,
text file”)
however, we are going to call it
“testfile.txt”.  file.write(“and this is another
 Just create the file and leave it
blank.
line.”)
 To manipulate the file, write the
following in your Python  file.write(“Why? Because
environment (you can copy and
paste if you’d like):
we can.”)
 file.close()
File Handling
 Python allows reading and writing to files # Syntax for opening a file
using the file object. file_object = open(“filename”, “mode”) where
 The open(filename, mode) function is file_object is the variable to add the file object.
used to get a file object.
 The mode can be read (r), write (w), # Example of reading an entire
append (a), read and write (r+ or w+), file
read-binary (rb), write-binary (wb), etc. >>>fp = open('file.txt','r')
 After the file contents have been read >>>content = fp.read()
the close function is called which closes >>>print content
the file object. This is a test file.
>>>fp.close()

# Example of reading line by line


# Example of reading lines in a loop
>>>fp = open('file1.txt','r')
>>>print( "Line-1: " , fp.readline()) >>>fp = open(’file1.txt’,’r’)
Line-1: Python supports more than >>>lines = fp.readlines()
one programming paradigms. >>>for line in lines:
>>>print ("Line-2: " , fp.readline()) print( line)
Line-2: Python is an interpreted
language. Python supports more than one programming
>>>fp.close() paradigms.
Python is an interpreted language.
Buffering in files
 Ifthe buffering value is set to 0, no
buffering takes place. If the buffering
value is 1, line buffering is performed while
accessing a file. If you specify the
buffering value as an integer greater than
1, then buffering action is performed with
the indicated buffer size
File Handling
# Example of reading a certain # Example of seeking to a certain
number of bytes position

>>>fp = open('file.txt','r') >>>fp = open('file.txt','r')


>>>fp.read(10) >>>fp.seek(10,0)
'Python sup' >>>content = fp.read(10)
>>>fp.close() >>>print content
ports more
# Example of getting the current >>>fp.close()
position of read

>>>fp = open('file.txt','r') # Example of writing to a file


>>>fp.read(10)
'Python sup' >>>fo = open('file1.txt','w')
>>>currentpos = fp.tell >>>content='This is an example of writing
>>>print currentpos to a file in Python.'
<built-in method tell of file object at >>>fo.write(content)
0x0000000002391390> >>>fo.close()
>>>fp.close()
write a Python program to read through the lines of the file, break each line into a list of
words, and then loop through each of the words in the line and count each word using a
dictionary

fname = raw_input('Enter the file name: ')


try:
fhand = open(fname)
except:
print 'File cannot be opened:', fname
exit()
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print counts
Classes
 Python is an Object-Oriented Programming (OOP) language. Python provides all the
standard features of Object Oriented Programming such as classes, class variables, class
methods, inheritance, function overloading, and operator overloading.
 Class
 A class is simply a representation of a type of object and user-defined prototype for
an object that is composed of three things: a name, attributes, and
operations/methods.
 Instance/Object
 Object is an instance of the data structure defined by a class.
 Inheritance
 Inheritance is the process of forming a new class from an existing class or base class.
 Function overloading
 Function overloading is a form of polymorphism that allows a function to have
different meanings, depending on its context.
 Operator overloading
 Operator overloading is a form of polymorphism that allows assignment of more than
one function to a particular operator.
 Function overriding
 Function overriding allows a child class to provide a specific implementation of a
function that is already provided by the base class. Child class implementation of the
overridden function has the same name, parameters and return type as the function
in the base class.
Classes
• The class has a documentation
General Syntax string, which can be accessed via
class ClassName: ClassName.__doc__.
'Optional class documentation • The class_suite consists of all the
string' class_suite component statements defining
class members, data attributes
and functions.

• There is a special method by the name __init__() which is called the class
constructor. The class constructor initializes a new instance when it is
created.
• The function __del__() is the class destructor
• The variable empCount is a class variable whose value is shared among
all the instances of this class. This can be accessed as
Employee.empCount from inside the class or outside the class.
• You declare other class methods like normal functions with the
exception that the first argument to each method is self. Python adds
the self argument to the list for you; you do not need to include it when
you call the methods
• Members declared without underscore are public
• Members declared with one underscore are protected
• Members declared with two underscores are private
WAP for adding two numbers using class
class num:
def __init__(self, aa, bb):
self.a = aa
self.b = bb
def add(self):
return self.a + self.b

e = num(8, 6)
print(e.add())

Output

14
Write a program to create and display an
employee data base using classes in python
class Employee:
‘’’Common base class for all employees’’’
empCount = 0
def __init__(self, n, s):
self.name = n
self.salary = s
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)

def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary )
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
Output
#This would create first object of Employee class" Name : Zara ,Salary: 2000
emp1 = Employee("Zara", 2000) Name : Manni ,Salary: 5000
#This would create second object of Employee class" Total Employee 2
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
Data Hiding
 Data Hiding
 One of the key parts of object-oriented programming is encapsulation, which
involves the packaging of variables and related functions in one simple-to-use
object: the instance of a class.
 A concept related to this is data hiding, which consists in hiding the
implementation details of a class. In this way the user interface of this class is
clean and more intuitive. In other programming languages, data hiding is
done by creating private methods and attributes, to which their external
access to the function is blocked. In Python, however, the philosophy is slightly
different “we are all consenting adults” and therefore there are no particular
restrictions on access. So there is nothing that can deprive an attribute or
method in such a way as to make it inaccessible to the outside of the
classroom.
 In Python, the so-called weakly-private methods have a single underscore (_)
prefixed in their name. This prefix indicates the presence of a private method,
which should not be used outside the class. But this is just a convention and
nothing avoids the opposite. The only real effect it has is to avoid importing
the method when using the wording
 from modulename import *
 Instead, there are methods and attributes, strongly private, that are
distinguished by the double underscore (__) as prefix in their name. Once a
method is marked with this double underscore, then the method will be really
private and will no longer be accessible from outside the class.
 However, these methods can still be accessed from the outside, but using a
different name
Data Hiding
class JustCounter:
__secretCount = 0 • Python protects those members
def count(self):
self.__secretCount += 1
by internally changing the name
print (self.__secretCount) to include the class name.
• You can access such attributes as
counter = JustCounter() object._className__attrName.
counter.count() • If you would replace your last line
counter.count()
print (counter.__secretCount)
as following, then it works for you-

Output print
1 (counter._JustCounter__secretCou
2 nt)
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute
'__secretCount'
Class Inheritance
 In this example parent is the base class and Child is the derived class.
The class Child inherits the attributes of the Parent class.

class Parent:
def __init__(self, a):
self.a = a
def print_var1(self):
print("The value of Parent class variables
are:")
print(self.a)
class Child(Parent):
def __init__(self, a, b):
Parent.__init__(self, a)
self.b = b
def print_var2(self):
print("The value of Child class variables
are:")
print(self.b) OutPut
X=Child(10,20) 10
X.print_var1() 20
X.print_var2()
Packages
# skimage package listing
 Python package is hierarchical file skimage/ Top level package
structure that consists of modules __init__.py Treat directory as a
and subpackages. package
 Packages allow better organization
of modules related to a single color/ color color
subpackage
application environment.
__init__.py
colorconv.py
colorlabel.py
rgb_colors.py

draw/ draw draw


subpackage
__init__.py
draw.py
setup.py

exposure/ exposure
subpackage
__init__.py
_adapthist.py
exposure.py

feature/ feature subpackage


__init__.py
Date/Time Operations
 Python provides several functions for date and time access and
conversions.
 The datetime module allows manipulating date and time in several ways.
 The time module in Python provides various time-related functions.
# Examples of manipulating with
date # Examples of manipulating with time
>>>from datetime import date
>>>import time
>>>now = date.today() >>>nowtime = time.time()
>>>print "Date: " + >>>time.localtime(nowtime)
now.strftime("%m-%d-%y") time.struct_time(tm_year=201, tm_mon=7,
Date: tm_mday=24, tm_ec=51, tm_wday=2, tm_yday=205,
tm_isdst=0)
>>>print "Day of Week: " +
now.strftime("%A") >>>time.asctime(time.localtime(nowtime))
Day of Week: Wednesday 'Wed Jul 24 16:14:51 2013'

>>>print "Month: " + >>>time.strftime("The date is %d-%m-%y. Today is a


now.strftime("%B") %A. It is %H hours, %M minutes and %S seconds now.")
Month: 'The date is 24-07-13. Today is a Wednesday. It is 16
hours, 15 minutes and 14 seconds now.'
>>>then = date(2013, 6, 7)
>>>timediff = now - then
>>>timediff.days
47
Python Packages of Interest for IoT
 JavaScript Object Notation (JSON): is an easy to
read and write data-interchange format. JSON is
often used for serializing and transmitting structured
data over a network connection – say between a
server and a web application. JSON supports
encoding and decoding of data
 Extensible Markup Language (XML): is a data
format for structure document interchange with,
parse / read / write features. The Python ‘minidom’
library provides an API / interface for XML
document interchange.
 HTTPLib2 and URLLib2 Python libraries with support
for post / request etc enable network / internet
programming
 Simple Mail Transfer Protocol (SMTP) Lib (SMTPLib) for
Python is for handling sending / routing eMails
HTTP GET request example using request

import requests

r = requests.get('http://httpbin.org/')
print(type(r))
print(r.status_code)
print(r.headers)
print(r.headers['content-type'])
#print(r.text)

Some of the methods it has are:

r.status_code is the HTTP status code. On success it is 200.

r.headers is a dictionary of all the entries in the header.


for example for the above request I got the following header:

{'content-length': '12150', 'server': 'nginx', 'connection': 'keep-alive', 'access-control-allow-credentials':


'true', 'date': 'Thu, 05 Jan 2017 09:45:02 GMT', 'access-control-allow-origin': '*', 'conte
Asking for JSON

import requests

r = requests.get('http://httpbin.org/ip')
print(r.headers['content-type'])
print(r.text)
data = r.json()
print(data)
print(data['origin'])

The content-type is
application/json

The text is a JSON string. In the case of the


{ "origin": "31.168.125.94" }

The json method converts the JSON string into a Python data structure. In our case it is a
dictionary holding a single key and the IP address of our computer as the value:
{u'origin': u'31.168.135.94'}

We can access the individual values (in this case the IP address), just as we do with any other
dictionary in Python:
data['origin']
Python HTTP Client Request – GET, POST

import http.client

connection =
http.client.HTTPSConnection("www.journaldev.com")
connection.request("GET", "/")
response = connection.getresponse()
print("Status: {} and reason: {}".format(response.status,
response.reason))

connection.close()
Output: Status: 200 and reason: OK
Getting the Header list from Response

import http.client
import pprint

connection =
http.client.HTTPSConnection("www.journaldev.c
om")
connection.request("GET", "/")
response = connection.getresponse()
headers = response.getheaders()
pp = pprint.PrettyPrinter(indent=4)
pp.pprint("Headers: {}".format(headers))
print(content)
max-age=0'), ('Expires', 'Mon, 22 Oct "
"2018 00:29:51 GMT'), ('Content-Type', 'text/html;
charset=UTF-8'), ('Link', "
'\'<https://www.journaldev.com/wp-json/>;
rel="https://api.w.org/"\'), '
"('X-LiteSpeed-Cache-Control', 'public,max-
age=604800'), ('X-LiteSpeed-Tag', "

"'0e81_URL.6666cd76f96956469e7be39d750cc7d
9,0e81_F,0e81_'), ('Etag', "
'\'"5093-1540168191;;;"\'), (\'X-Litespeed-
Cache\', \'miss\'), '
"('Transfer-Encoding', 'chunked'), ('Date', 'Mon,
22 Oct 2018 00:29:51 GMT'), "
"('Server', 'LiteSpeed'), ('Vary', 'User-Agent'), ('X-
Content-Type-Options', "
"'nosniff'), ('X-XSS-Protection', '1; mode=block'), "
"('Strict-Transport-Security', 'max-age=31536000;
includeSubDomains'), "
'(\'Connection\', \'Keep-Alive\'), (\'Alt-Svc\',
\'quic=":443"; ma=2592000; '
'v="35,39,43"\')]')
Python HTTP POST

import http.client
import json

conn =
http.client.HTTPSConnection('www.httpbin.org')
OUTPUT:{
"args": {},
headers = {'Content-type': 'application/json'} "data": "{\"text\": \"Hello HTTP #1 **cool**,
and #1!\"}",
foo = {'text': 'Hello HTTP #1 **cool**, and #1!'}
"files": {},
json_data = json.dumps(foo) "form": {},
"headers": {
conn.request('POST', '/post', json_data, headers)"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "43",
response = conn.getresponse()
"Content-Type": "application/json",
print(response.read().decode()) "Host": "www.httpbin.org"
},
"json": {
"text": "Hello HTTP #1 **cool**, and #1!"
},
"origin": "223.237.223.57",
"url": "https://www.httpbin.org/post"
}
Further Reading

 Code Academy Python Tutorial,


http://www.codecademy.com/tracks/python
 Google's Python Class,
https://developers.google.com/edu/python/
 Python Quick Reference Cheat Sheet,
http://www.addedbytes.com/cheat-sheets/python-
cheat-sheet/
 PyCharm Python IDE,
http://www.jetbrains.com/pycharm/

Potrebbero piacerti anche