Network Programming Control Flow Functions OOP in Python PDF
Document Details
Uploaded by Ameera
University of Sharjah
Dr. Ala Altaweel
Tags
Related
- Unit 1 Python Basics, Control Structures, and Other Features PDF
- Programming in Python for Business Analytics (BMAN73701) Lecture Notes PDF
- SDU University CSS 115: Python Programming Fundamentals Fall 2024 Lecture 4 PDF
- Python Programming Notes PDF
- SYSC 2006: Imperative Programming Lecture 3 - Flow of Control (Carleton University)
- Biotech4bi3 - Lecture 1 - Python Introduction PDF
Summary
This document is a lecture on Python programming, specifically focusing on control flow, functions, and object-oriented programming (OOP). It covers fundamental concepts like if-else statements, different types of loops, and includes examples and exercises.
Full Transcript
Network Programming: Control Flow, Functions, and OOP in Python Dr. Ala Altaweel University of Sharjah Department of Computer Engineering [email protected] 1 Agenda Introduction Running Python Python Programmi...
Network Programming: Control Flow, Functions, and OOP in Python Dr. Ala Altaweel University of Sharjah Department of Computer Engineering [email protected] 1 Agenda Introduction Running Python Python Programming Data types Lab1 assignment Control flows Functions, Modules Lab2 Assignment Files, OOP and Classes 2 If Else Fundamental building block of If Else Conditional statement Executed if answer is True Executed if answer is False 3 If Else example Try running the example below. What do you get? 4 Indentation matters! Code is grouped by its indentation Indentation is the number of whitespace or tab characters before the code If you put code in the wrong block, then you will get unexpected behavior 5 Extending if‐else blocks We can add infinitely more if statements using elif elif = else + if which means that the previous statements must be false for the current one to evaluate to true 6 Nested If if, if/else, if/elif/else if a == 0: print "zero!" elif a < 0: print "negative!" else: print "positive!" Notes: blocks delimited by indentation! colon (:) used at end of lines containing control flow keywords 7 Comparison Operators on: int, float, string i and j are variable names Comparisons below evaluate to Boolean i > j i >= j i < j i = 8) and (ageb and a>c) and (a != b and a != c)): print(a, " is the largest") elif((b>a and b>c) and (b != a and b != c)): print(b, " is the largest") elif((c>a and c>b) and (c != a and c != b)): print(c, " is the largest") else: print("entered numbers are equal") 10 Homework! What would happen if many conditions are True? a = 8 if(a%2 == 0): print(a, " is even") elif(a%4 == 0): print(a, " is divisible by 4") elif(a%8 == 0): print(a, " is divisible by 8") 11 For loop Allows us to iterate over a set amount of variables within a data structure. During that we can manipulate each item however we want Again, indentation is important here! 12 Example Say we want to go over a list and print each item along with its index What if we have much more than 4 items in the list, say, 1000? 13 Example Now with a for loop Saves us writing more lines Doesn't limit us in term of size 14 Numerical for loop for loops for a in range(10): print a really a "foreach" loop 15 Numerical for loop 16 Common for loop idiom: a = [3, 1, 4, 1, 5, 9] for i in range(len(a)): print a[i] 17 While loop Another useful loop. Like the for loop A while loop doesn't run for a predefined number of iterations, like for loop. Instead, it stops as soon as a given condition becomes true/false 18 While loop while loops a = 10 while a > 0: print a a -= 1 19 Break statement Allows us to go(break) out of a loop preliminary Adds a bit of controllability to a while loop Usually used with an if Can also be used in a for loop 20 Quick homework How many times are we going to execute the while loop? 21 While loop Common while loop idiom: f = open(filename, "r") while True: line = f.readline() if not line: break # do something with line 22 For versus While loop For loops While loops Know number of Unbounded number of iterations iterations Can end early via break Can end early via break Uses a counter Can use a counter but must Can rewrite a for loop initialize before loop and using a while loop incremented/ decremented inside loop May not be able to rewrite a while loop using a for loop 23 Control flow: continue keyword like in C: continue keyword is used to end the current iteration in a for loop (or a while loop) and continues to the next iteration. for x in [0, 1, 2, 3, 4, 5]: if (x==1): continue else: print (x) print ("Done with iteration with: " + str(x) + "\n") 24 Control flow: continue keyword Output of previous code: 0 Done with iteration with: 0 2 Done with iteration with: 2 3 Done with iteration with: 3 4 Done with iteration with: 4 5 Done with iteration with: 5 25 Control flow: pass keyword Used as a placeholder for future code When pass statement is executed, nothing happens, but we avoid getting an error when empty code is not allowed Empty code is not allowed in loops, function definitions, class definitions, or in if statements pass keyword: if a == 0: pass # do nothing else: # whatever 26 Control flow: pass keyword for x in [0, 1, 2, 3, 4, 5]: if (x==1): pass else: print (x) print ("Done with iteration with: " + str(x) + "\n") Output of above code: 0 Done with iteration with: 0 Done with iteration with: 1 2 Done with iteration with: 2 3 Done with iteration with: 3 4 Done with iteration with: 4 5 27 Done with iteration with: 5 Continue versus Pass 28 Agenda Introduction Running Python Python Programming Data types Lab1 assignment Control flows Functions, Modules Lab2 Assignment Files, OOP and Classes 29 Functions A function is a group of statements that exist within a program for the purpose of performing a specific task Since the beginning of this semester, we have been using several Python’s built‐in functions, including: print() range() len() reverse() in List … etc 30 Functions Most programs perform tasks that are large enough to be broken down into subtasks Programmers often organize their programs into smaller, more manageable chunks by writing their own functions Instead of writing one large set of statements, we break down a program into several small functions Functions allows to “divide and conquer” a programming problem 31 Good programming and Functions More code not necessary a good thing Measure good programmers by the amount of functionality Use functions …. In programming, divide code into functions are self‐contained used to break up code intended to be reusable keep code organized keep code coherent easy to hand‐over and debugging used many times but debugged once 32 Defining Functions Functions, like variables must be named and created before you can use them The same naming rules apply for both variables and functions You can’t use any of Python’s keywords No spaces The first character must be A‐Z or a‐z or the “_” character After the first character you can use A‐Z, a‐z, “_” or 0‐9 Uppercase and lowercase characters are distinct 33 Defining Functions Functions are not run in a program until they are “called” or “invoked” in a program Function characteristics: has a name has parameters (0 or more) has a docstring (optional but recommended) has a body returns something 34 How to write and call/invoke a funcation def is_even(i): """ Input: i, a positive int Returns True if i is even, otherwise False """ print ("inside is_even function") return i%2 == 0 print(is_even(5)) 35 In the Function Body def is_even(i): """ Input: i, a positive int Returns True if i is even, otherwise False """ print ("inside is_even function") return i%2 == 0 print(is_even(5)) 36 Some notes on functions When we run a function, we say that we “call” it Once a function has completed, Python will return back to the line directly after the initial function call When a function is called programmers say that the “control” of the program has been transferred to the function The function is responsible for the program’s execution Functions must be defined before they can be used In Python we generally place all of our functions at the beginning of our programs 37 Flow of Execution Python interpreter runs each line serially from the top of the file 38 Flow of Execution 39 Flow of Execution 40 Flow of Execution 41 Flow of Execution 42 Flow of Execution with Functions 43 Flow of Execution with Functions 44 Flow of Execution with Functions 45 Flow of Execution with Functions 46 Flow of Execution with Functions 47 Flow of Execution with Functions 48 Flow of Execution with Functions 49 Flow of Execution with Functions 50 Flow of Execution with Functions 51 Flow of Execution with Functions 52 Variable Scope Formal parameter gets bound to the value of actual parameter when the function is called New scope/frame/environment created when enter a function def f(x): x = x+1 print(in f(x): x=, x) return x x = 3 z = f(x) 53 Variable Scope def f(x): x = x+1 print("in f(x): x=", x) return x x = 3 z = f(x) 54 Variable Scope def f(x): x = x+1 print("in f(x): x=", x) return x x = 3 z = f(x) 55 Variable Scope def f(x): x = x+1 print("in f(x): x=", x) return x x = 3 z = f(x) 56 Variable Scope def f(x): x = x+1 print("in f(x): x=", x) return x x = 3 z = f(x) 57 Warning, if no return statement Python returns the value None, if no return given, Represents the absence of value def is_even(i): """ Input: i, a positive int Does not return anything """ print ("inside is_even function") i%2 == 0 x = is_even(3) print(x) Output of above code: inside is_even function None 58 return versus print return print return only has meaning print can be used outside inside a function functions only one return executed can execute many print inside a function statements inside a function code inside function but code inside function can be after return statement not executed after a print executed statement has a value associated with has a value associated with it, it, given to function caller outputted to the console 59 Multiple Functions Define and call several functions def hello(): print ("Hello there!") def goodbye(): print ("See you later!") hello() goodbye() 60 Calling functions inside functions def main(): print ("I have a message for you.") message() print(“Goodbye!") def message(): print (“This class is interesting!") main() 61 Passing Arguments to a Function Sometimes it’s useful to not only call a function but also send it one or more pieces of data as an argument This process is identical to what we’ve been doing with the built‐in functions we have studied so far string = “This course is awesome, isn't it?" substring = "is" count = string.count(substring) # send 1 argument a = range(5) # [0,1,2,3,4] # send 1 argument a.append(5) # [0,1,2,3,4,5] # send 1 argument a.insert(0, 5.5) # [5.5,0,1,2,3,4,5] # send 2 arguments 62 Passing Arguments to a Function When passing arguments, you need to let your function know what kind of data it should expect in your function definition You can do this by establishing a variable name in the function definition This variable will be auto declared every time you call your function and will assume the value of the argument passed to the function def sum(num1, num2, num3): sum = num1+num2+num3 return sum print(sum(100,90,90)) print(sum("This", " is ", " an example!")) print(sum([1,2], [3,4], [5,6])) Output of above code: 280 This is an example! [1, 2, 3, 4, 5, 6] 63 Argument Mechanics When we pass an argument to a function in Python we are actually passing it’s “value” into the function, and not an actual variable def change_me(v): print ("function got:", v) v = 10 print ("argument is now:", v) myvar = 5 print ("starting with:", myvar) change_me(myvar) print ("ending with:", myvar) Above code will print: starting with: 5 function got: 5 argument is now: 10 ending with: 5 64 Argument Mechanics We call the behavior in the last slide “passing by value” Essentially creating two copies of the data that is being passed, One that stays in the main program and one that is passed as an argument into the function This behavior set up a “one way” communication mechanism, that is, Send data into a function as an argument, but the function cannot communicate back by updating the argument in any way But how to communicate back to the caller??!! 65 Main program: Ahmad Function: Ahmad Main program: Ahmad Function: Ahmad Global Variables When you create a variable inside a function we say that the variable is “local” to that function This means that it can only be accessed by statements inside the function that created it When a variable is created outside all of your functions it is considered as a “global variable” Global variables can be accessed by any statement in your program file, including by statements in any function name = "Ahmad" def showname(): print("Function: ", name) print ("Main program: ", name) showname() Above code will print: Main program: Ahmad 66 Function: Ahmad Global Variables In order to change a global variable inside a function, we must first tell Python that we wish to do this using the “global” keyword inside the function name = "Ahmad" def showname(): global name print("Function1: ", name) name = "Ali" print("Function2: ", name) print ("Main program 1: ", name) showname() print ("Main program 2: ", name) Above code will print: Main program 1: Ahmad Function1: Ahmad Function2: Ali 67 Main program 2: Ali Notes on Global Variables Global Variable can make debugging difficult Functions that use global variables are generally dependent on them, hence, the code is less portable However, there are many situations where using global variables make a lot of sense # Remote server IP and port# REMOTE_SERVER_IP = "192.168.34.4" REMOTE_SERVER_PORT = 22223 # Default TTL for a packet, 1 day in seconds DEFAULT_PKT_TTL = 86400 # Default buffer size for data 5MB DEFAULT_DATA_BUF_SIZE = 5242880 68 Function Example Write a Python function, string_test, that takes a string as an argument and calculate the number of upper‐case letters and lower‐ case letters Write a Python code that keeps accepting a string input from the user and call the string_test function Once the user enters “quit”, the program should terminates 69 Function Example def string_test(s): d={"UPPER_CASE":0, "LOWER_CASE":0} for c in s: if c.isupper(): d["UPPER_CASE"]+=1 elif c.islower(): d["LOWER_CASE"]+=1 else: pass print ("Original String : ", s) print ("No. of Upper case Characters : ", d["UPPER_CASE"]) print ("No. of Lower case Characters : ", d["LOWER_CASE"]) while (True): print ("Hello there, please enter a string:") entered = raw_input() if (entered == "quit"): print ("You entered quit, Goodbye!") break string_test(entered) 70 Agenda Introduction Running Python Python Programming Data types Lab1 assignment Control flows Functions, Modules Lab2 Assignment Files, OOP and Classes 71 Modules in Python Python, like other programming languages come with a pre‐ packaged standard library of functions that are designed to make programmer’s job easier Some of these functions are built right into the “core” of Python (print, input, range, etc.) Others, are more specialized functions that are stored in a series of files called “modules” Python can access these modules upon request by using the “import” statement import random import socket 72 Built‐In Modules in Python On Ubuntu, you can find these modules under: /usr/lib/python2.7/ 73 Importing Modules in Python – “black box” model import statement tells Python interpreter to load the functions that exist within a specific module into memory and make them available in your code Because we don’t see the inner workings of a function inside a module, we call them “black boxes” A “black box” describes a mechanism that accepts input(s), performs an operation that can’t be seen using that input, and produces output(s) Input(s) Output(s) 74 Functions in Built‐In Modules We call functions that exist within a module by using “dot notation” to tell Python to run a function that exists in that module Example: num = random.randint(1,5) # return a random integer in [1, 5] range s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) """ In the above line, we create a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4. SOCK_STREAM means this is a connection‐oriented TCP protocol """ 75 Help() Function for Built‐In Modules You can list the functions that exist in a particular module by using the help() function The help() function takes one argument (a string that represents the name of the module) and returns the user manual for that module You need to do the following: $ import modulename $ help (modulename) 76 User‐Defined Modules in Python You can create your own modules that you can populate with your own functions: 1) Create a new python script (i.e. “myfunctions.py”) 2) Place your function definitions in this script 3) Create a second python script (i..e “myprogram.py”) 4) Import your function module using the import statement: $ import myfunctions Call your functions using dot notation $ myfunctions.function1() $ myfunctions.function2() 77 What is the main() function in python Most programming languages have a special function, main(), which is the entry point to execute any program Python interpreter runs each line serially from the top of the file and has no explicit main() function However, Python offers a convention to define the entry point of execution The __name__ variable is a special built‐in Python variable that shows the name of the current module It has different values depending on where we execute the Python file As a script Or, as a module 78 Running Python File as a Script Suppose we have a Python file called helloworld.py: print(__name__) If we run helloworld.py from the command line, as a Python script $ python helloworld.py The value of the variable __name__ is set to __main__. The output of the above program will be: __main__ 79 Running Python File as a Module We can also run a Python file as a module by importing it into another Python program Suppose we have a Python file called main.py in the same directory as the heloworld.py file. It has the following content: Import helloworld Running main.py will give the following output: helloworld Here, importing a module runs all the code in the module file Instead of displaying __main__, the program displays the name of the module, helloworld This is because, in the context of running a Python file as a module, the name of the module itself is assigned to the __name__ variable 80 Using if conditional with __name__ Based on __name__, we can use the if conditional clause to run the same Python file in different ways Suppose helloworld.py: def main(): print("Hello World") if __name__=="__main__": main() If we run it as a Python script via the command line, it will give: Hello World If we run it as a module by importing it in main.py file, no output is displayed since the main() function is not called main() is a customized function in helloworld.py that is only executed when helloworld.py is run as a standalone script not as an imported module This is the standard way to explicitly define the main() function in Python and it is one of the popular use cases of __name__ variable 81 Why use modules? Code reuse Routines can be called multiple times within a program Routines can be used from multiple programs Namespace partitioning Group data together with functions used for that data Implementing shared services or data Can provide global data structure that is accessed by multiple subprograms 82 Agenda Introduction Running Python Python Programming Data types Lab1 assignment Control flows Functions, Modules Files, Lab2 Assignment OOP and Classes 83 Files in Programming Languages A file represents a sequence of bytes on the disk (file system) where a group of related data is stored File is created for permanent storage of data. It is a ready‐made structure In any programming language, programmers need to be able to manipulate files: Open a file Read from a file Write into a file Append to a file Close a file 84 File I/O in Python input = open("data", "r") Open the file for input S = input.read() Read whole file into one String S = input.read(N) Reads N bytes (N >= 1) L = input.readlines() Returns a list of line strings 85 Files: Output output = open("data", "w") Open the file for writing output.write(S) Writes the string S to file output.writelines(L) Writes each of the strings in list L to file output.close() Manual close 86 open() and file() These are identical: f = open(filename, "r") f = file(filename, "r") The open() version is older The file() version is the recommended way to open a file now uses object constructor syntax (next topic: OOP in Python) 87 Split method and its application in files In general, most of the files are written in standard format: Comma Separated Value format (CSV) Hash separated Value format, etc. The split() method splits a string into a list Syntax: String.split(separator, maxsplit) You can specify the separator, default is any whitespace maxsplit is optional, it specifies how many splits to do. Default is ‐1 (all occurrences) txt = "hello, my name is Peter, I am 26 years old" x = txt.split(", ") print(x) Above code will print: ['hello', 'my name is Peter', 'I am 26 years old'] 88 Split method and its application in files txt = "hello, my name is Peter, I am 26 years old" x = txt.split(" ") print(x) Above code will print? Try it as a homework 89 Files: Exercise1 Example Write a function input_stats that accepts a file name as a parameter and reports the longest line in that file Example input file, file.txt: An important approach to master this course is to practice as much as possible, for example, try to run each code we put in the slides yourself and find out if they meets the expected output! Expected output: >>> input_stats("file1.txt") longest line = 55 characters is to practice as much as possible, for example, try 90 Files: Exercise1 Solution def input_stats(filename): input = file(filename, 'r') content = input.readlines() longest = "" for line in content: if len(line) > len(longest): longest = line print("Longest line =" + str(len(longest)) + " characters") print(longest) input_stats("file1.txt") 91 Files: Exercise2 Example Suppose we have the below file named, students_record.t, that is stored at the UOS registration system: User Name,User ID,Full Name,Email,Address,Major Ahmad, ahmad5632, 'Ahmad Ali', [email protected], '12th street, Abu Dhabai, UAE', "CE" Nayef, nayef4567, 'Nayef Mustafa', [email protected], 'Alwahda Street, Sharajah, UAE', "EE" Fatima, fatima3487, 'Fatima Salim', [email protected], '875 Avenue, Dubai, UAE', "CS" John, john1420, 'John Frank', [email protected], '15oo southwest pkwy, TX, USA', "EE" We want to write a Python code that reads this file and generate another file with only the ‘User ID’ and the ‘Email’ of each student The output of the Python code should be a file named, students_record_filtered.t : ahmad5632, [email protected] nayef4567, [email protected] fatima3487, [email protected] john1420, [email protected] 92 Files: Exercise2 Solution in_file = file('students_record.t', 'r') lines = in_file.readlines() IDs_Emails = [] for l in lines: if('User Name' in l): continue items = l.split(', ') IDs_Emails.append(items + ", " + items + "\n") out_file = file('students_record_filtered.t', 'w') out_file.writelines(IDs_Emails) out_file.close() 93 Agenda Introduction Running Python Python Programming Data types Lab1 assignment Control flows Functions, Modules Lab2 Assignment Files, OOP and Classes 94 Objects in Python Python supports many kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13] {"CA": "California", "TX": " Texas"} Each is an object, and every object has: a type an internal data representation (primitive or composite) a set of procedures for interaction with the object An object is an instance of a type 1234 is an instance of an int "hello"is an instance of a string 95 Object Oriented Programming (OOP) EVERYTHING IN PYTHON IS AN OBJECT (and has a type) Can create new objects of some type Can manipulate objects Can destroy objects explicitly using del or just “forget” about them python system will reclaim destroyed or inaccessible objects –called “garbage collection” 96 What are Objects? Objects are a data abstraction that captures… (1) an internal representation through data attributes (2) an interface for interacting with object through methods (a.k.a. procedures/functions) defines behaviors but hides implementation 97 Example: [1, 2, 3, 4] has type list How are lists represented internally? Linked lists of cells how to manipulate lists? L[i], L[i:j], + len(), min(), max(), del(L[i]) L.append(), L.extend(), L.count(), L.index(), L.insert(), L.pop(), L.remove(), L.reverse(), L.sort() Internal representation should be private Correct behavior may be compromised if you manipulate internal representation directly 98 Advantages of OOP bundle data into packages together with procedures that work on them through well‐defined interfaces divide‐and‐conquer development implement and test behavior of each class separately increased modularity reduces complexity Classes make it easy to reuse code many Python modules define new classes each class has a separate environment (no collision on function names) inheritance allows subclasses to redefine or extend a selected subset of a superclass’ behavior 99 Creating and using your own types (classes) Make a distinction between creating a class and using an instance of the class Creating the class involves defining the class name defining class attributes for example, someone wrote code to implement a list class Using the class involves creating new instances of objects doing operations on the instances for example, L=[1,2] and len(L) 100 Define Class in Python Use the class keyword to define a new type class Coordinate (ClassName): #define attributes here Similar to def, indent code to indicate which statements are part of the class definition The word ClassName represents another class name, and it means that Coordinate class inherits all its attributes (inheritance is not the scope of this course, we will use simple cases of it in future lectures) Coordinate is a subclass of ClassName ClassName is a superclass of Coordinate 101 What are Attributes? data and procedures that “belong” to the class data attributes think of data as other objects that make up the class for example, a coordinate is made up of two numbers methods (procedural attributes) think of methods as functions that only work with this class how to interact with the object for example, you can define a distance between two coordinate objects but there is no meaning to a distance between two list objects 102 How to create an instance of a class in Python First, we must create an instance of Coordinate Use a special method called __init__ to initialize some data attributes class Coordinate (ClassName): def __init__(self, x, y): self.x = x self.y = y 103 How to create an instance of a class in Python c = Coordinate(3, 4) origin = Coordinate(0, 0) print(c.x) print(c.y) Data attributes of an instance are called instance variables Don’t provide argument for self, Python does this automatically 104 What is a method? Procedural attribute, like a function that works only with this class Python always passes the object as the first argument convention is to use self as the name of the first argument of all methods The “.”operator is used to access any attribute a data attribute of an object a method of an object 105 Define a method for the Coordinate class class Coordinate(object): def__init__(self, x, y): self.x= x self.y= y def distance(self, other): x_diff_sq= (self.x‐other.x)**2 y_diff_sq= (self.y‐other.y)**2 return (x_diff_sq + y_diff_sq)**0.5 Apart from self and dot notation, methods behave just like functions (take params, do operations, return) 106 How to use a method class Coordinate(object): # code here Using the class: Equivalent to: Conventional way c = Coordinate(3, 4) c = Coordinate(3, 4) zero = Coordinate(0, 0) zero = Coordinate(0, 0) print(c.distance(zero)) print(Coordinate.distance(c, zero)) 107 Print an object in Python c = Coordinate(3, 4) print(c) Above code will print something like below (based on Python interpreter) __main__.Coordinateobject at 0x7fa918510488> uninformative print representation by default define a __str__ method for a class Python calls the __str__ method when used with print on your class object The programmer can choose what and how to print For example, for a Coordinate object, want to show 108 Defining a Print Method class Coordinate(object): def__init__(self, x, y): self.x= x self.y= y def distance(self, other): x_diff_sq= (self.x‐other.x)**2 y_diff_sq= (self.y‐other.y)**2 return (x_diff_sq + y_diff_sq)**0.5 def __str__ (self): return "" 109 Special Operators +, ‐, ==, , len(), print, and many others Like print, the Python programmer can override the special operators to work with their classes Define them with double underscores before/after __add__(self, other) self + other __sub__(self, other)self - other __eq__(self, other) self == other __lt__(self, other) self < other __len__(self) len(self) __str__(self) print self …etc. 110 Example1: Class in Python Create a new type to represent a number as a fraction Internal representation is two integers numerator denominator Interface a.k.a. methods a.k.a how to interact with Fraction objects add, subtract print representation, convert to a float invert the fraction 111 Example1: Class in Python ################### ## Simple class to represent fractions ################### class Fraction(): """ A number represented as a fraction """ def __init__(self, num, denom): """ num and denom are integers """ self.num = num self.denom = denom def __str__(self): """ Retunrs a string representation of self """ return str(self.num) + "/" + str(self.denom) def __add__(self, other): """ Returns a new fraction representing the addition """ top = self.num*other.denom + self.denom*other.num bott = self.denom*other.denom return Fraction(top, bott) 112 Example1: Class in Python def __sub__(self, other): """ Returns a new fraction representing the subtraction """ pass # left as a self‐study homework def __float__(self): """ Returns a float value of the fraction """ return self.num/self.denom def inverse(self): """ Returns a new fraction representing 1/self """ return Fraction(self.denom, self.num) a = Fraction(1,4) b = Fraction(3,4) c = a + b # c is a Fraction object print(a) ¼ print(b) ¾ print(c) 16/16 print(Fraction.__float__(c)) 1 print(b.inverse()) 4/3 113 Example2: Class in Python Create a new type to represent a set of integers in Python Internal representation is list of integers Interface a.k.a. methods a.k.a how to interact with set objects insert element, check membership remove element, print check equality of two set objects 114 Example2: Class in Python ############## ## EXAMPLE: a set of integers as class ############## class intSet(object): """ An intSet is a set of integers The value is represented by a list of ints, self.vals Each int in the set occurs in self.vals exactly once """ def __init__(self): """ Create an empty set of integers """ self.vals = [] def insert(self, e): """ Assumes e is an integer and inserts e into self """ if not e in self.vals: self.vals.append(e) def member(self, e): """ Assumes e is an integer Returns True if e is in self, and False otherwise """ return e in self.vals 115 Example2: Class in Python def remove(self, e): """ Assumes e is an integer and removes e from self Return Error e is not in self """ if self.member(e): self.vals.remove(e) return True else: return False def __str__(self): """ Returns a string representation of self """ self.vals.sort() ret='{' for e in self.vals: ret += str(e) + ',' if(len(ret)>1): ret = ret[:‐1] ret += '}' return ret def __eq__(self, other): """ Return True if the two sets are equal, false otherwise """ for e in self.vals: if (other.member(e) == False): return False for e in other.vals: if (self.member(e) == False): return False return True 116 Example2: Class in Python s = intSet() print(s) {} s.insert(3) s.insert(4) s.insert(3) print(s) {3,4} print(s.member(3)) True print(s.member(5)) False s.insert(6) print(s) {3,4,6} print(s.remove(3)) True print(s) {4,6} print(s.remove(10)) False print(s) {4,6} t = intSet() t.insert(6) t.insert(4) print(s==t) True t.remove(6) print(t) {4} print(s==t) False t.insert(6) print(s==t) True t.insert(7) print(s==t) False 117 OOP Summary class ‐‐ a template for building objects instance ‐‐ an object created from the template (an instance of the class) method ‐‐ a function that is part of the object and acts on instances directly constructor ‐‐ special "method" that creates new instances 118 "Special" methods All start and end with __ (two underscores) Most are used to emulate functionality of built‐in types in user‐defined classes e.g. operator overloading __add__, __sub__, __mult__,... For more info, see python docs 119 More self‐study Homework? Implement a class that represent a user‐ defined Dictionary in Python Implement a class that represent a user‐ defined Complex Number in Python Implement a class that represent a user‐ defined Stack in Python..etc. 120 References Python Homepage http://www.python.org Python Tutorial http://docs.python.org/tutorial/ Python Documentation http://www.python.org/doc Python Library References http://docs.python.org/release/2.5.2/lib/lib.html 121