You are on page 1of 14

Enterprise Software Engineering

LECTURE 3 PYTHON PROGRAMMING (Lists, Dictionaries & OOP)

PG 1

Lists

Lists are similar to arrays in other languages like C/Java etc.

Along-with dictionaries, lists are one of the two most important data structures in python. Many python functions use and return lists.

But these are smart arrays, as these can grow and each element of an array can be of different type including objects and other lists etc.

If you try to access data on a non-existent list index, IndexError is raised.

Example: my_list = [1, 3, 5, 'A', 'B', ['another', 'list'] ]

Elements of a list can be accessed the same way as other languages using square brakets

print(my_list[0])

#prints 1

print(my_list[5][1]) #prints list

PG 2

Lists - Slicing

You can get slices/sub-lists from a list by specifying a range within a list

Examples:
my_list = [1, 3, 5, 'A', 'B', ['another', 'list'] ] new_list = my_list[0:3] #new list is [1,3,5] print(my_list[:5]) print(my_list[3:]) # prints [1, 3, 5, 'A', 'B'] # prints ['A', 'B', ['another', 'list']]

sublist = my_list[-1] # sublist contains ['another', 'list'] To add elements to a list, use the append method Example: my_list.append('another item') Strings also behave like lists so list slicing works with strings too Example: "Hello World"[3:8] #prints 'lo Wo'

PG 3

Lists - Iteration

To iterate all the elements in a list, use the for loop Example: mylist = ['a', 1, 2, 3, 'b'] for item in mylist: print(item)

For iterating thorough nested lists, use nested for loops Example: my_2D_list = [ [ 'Person A', 99, 'Student'], [ 'Person B', 19, 'Professor'], [ 'Person C', 30, 'Lecturer'], [ 'Person D', 50, 'Guard'] ] for row in my_2D_list: for col in row: print col, print

PG 4

Dictionaries Dictionaries are collections of data stored as key-value pairs Data items are accessed or added using their key names given in square brackets If a key does not exist and is accessed KeyError is raised

Use a dictionary object's has_key() method or the in operator to check if a key exists.

Example: my_dict = {'name': 'Anonymous', 'age': 99}

OR my_dict2 = dict(name='anonymous', age=99) print my_dict['name'] print my_dict2['age'] # prints Anonymous # prints 99 #adding another item to the dictionary

my_dict['profession'] = 'Sleeping' my_dict.has_key('name') 'name' in my_dict

# returns True # returns True


PG 5

Lists - Iteration

There are two common methods used to iterate/traverse through all the items in a dictionary.

Example: my_dict = {'name': 'Anonymous', 'age': 99, 'profession': 'student of F09'}

#method 1 for key in my_dict: print key, my_dict[key]

#method 2 for key, val in my_dict.iteritems(): print key, val

PG 6

A More Useful Example

records = [ {'name': 'ABC', 'reg_no': 1000, 'attendance': 20}, {'name': 'XYZ', 'reg_no': 1001, 'attendance': 26}, {'name': 'KDF', 'reg_no': 1002, 'attendance': 30} ]

print("Name\tReg. No\tAttendance") for record in records: print ( "%s\t%i\t%s" % \ (record['name'], record['reg_no'], record['attendance']) )

PG 7

A More Useful Example - Output

Name ABC XYZ KDF

Reg. No Attendance 1000 1001 1002 20 26 30

PG 8

Break

PG 9

Object Oriented Programming - Classes

Python provides excellent OOP facilities to developers. To create a class use the syntax:
class class_name[(parent_class_name)]: #class properties my_prop = value

#constructor def __init__(self): #constructor code

#destructor
def __del__(self): #destructor code

#other class methods etc.


PG 10

Object Oriented Programming Classes Some points

If a class has no parent class it can inherit from the object class

Providing a constructor or a destructor is not required, define these if you need them

A constructor can take arguments

self is a special keyword referring to the current object, all class methods including constructors and destructors should use self as the first argument.

Within the class code refer to all class properties using the self keyword.

Another great thing in python is that objects can have additional methods and properties than just those defined in their class.

Python supports multiple inheritance, that is, a class can have multiple parent classes unlike Java.

PG 11

Object Oriented Programming Classes Example

Please refer to the oop.py file provided with this lecture

Demonstrates the use of classes Demonstrates inheritance and multiple inheritance Demonstrates usage of object attributes by adding an extra property to the bush object

PG 12

Object Oriented Programming Polymorphism

Polymorphism (meaning "having multiple forms") in OOP is referred to the methodology to use the same calling mechanism (for example same function name) and getting different processing based on the data type of parameters passed or the type of object for which the function/method was called.

In python, there is no need to overload functions/methods for working with various data types as python is dynamically typed so no such use of polymorphism is required

Method based polymorphism can be used similar to other languages

Refer to the attached polymorphism.py file to see example of class method polymorphism

PG 13

Q&A

PG 14

You might also like