Computer Science 111 Fundamentals of Programming I

Slides:



Advertisements
Similar presentations
Write a program step by step. Step 1: Problem definition. Given the coordinate of two points in 2-D space, compute and print their straight distance.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
P3- Represent how data flows around a computer system
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
Utilizing the GDB debugger to analyze programs Background and application.
Computer Science 111 Fundamentals of Programming I Files.
Computer Science 111 Fundamentals of Programming I Introduction to Digital Image Processing.
CS 0008 Day 2 1. Today Hardware and Software How computers store data How a program works Operators, types, input Print function Running the debugger.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 17 Reading and Writing Files 5/10/09 Python Mini-Course: Lesson 17 1.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
Computer Science 111 Fundamentals of Programming I More Data Modeling.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Python Programming Using Variables and input. Objectives We’re learning to build functions and to use inputs and outputs. Outcomes Build a function Use.
Computer Science 111 Fundamentals of Programming I Persistent Data Models Object Serialization.
Networks and Client/Server Applications Handling Multiple Clients Concurrently.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Python Let’s get started!.
1 CSC 221: Introduction to Programming Fall 2011 Input & file processing  input vs. raw_input  files: input, output  opening & closing files  read(),
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 Essential Computing for Bioinformatics Bienvenido Vélez UPR Mayaguez Lecture 3 High-level Programming with Python Part III: Files and Directories Reference:
Kanel Nang.  Two methods of formatting output ◦ Standard string slicing and concatenation operations ◦ str.format() method ie. >>> a = “The sum of 1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Topic: File Input/Output (I/O)
Lesson 08: Files Class Participation: Class Chat: Attendance Code 
similar concepts, different syntax
Introduction to Programming
Networks and Client/Server Applications
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Python Let’s get started!.
Computer Programming Fundamentals
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Python’s input and output
Fundamentals of Programming I Design with Functions
IST256 : Applications Programming for Information Systems
Fundamentals of Programming I More Data Modeling
CSC 131: Introduction to Computer Science
Fundamentals of Programming I Introduction to Digital Image Processing
Exceptions and files Taken from notes by Dr. Neil Moore
Topics Introduction to File Input and Output
File IO and Strings CIS 40 – Introduction to Programming in Python
Lesson 08: Files Topic: Introduction to Programming, Zybook Ch 7, P4E Ch 7. Slides on website.
Fundamentals of Programming I Files
Exceptions and files Taken from notes by Dr. Neil Moore
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
Introduction to Python: Day Three
Introduction to Programming
Tutorial: The Programming Interface
Fundamentals of Programming I Commonly Used Methods More Modeling
Lesson 08: Files Class Chat: Attendance: Participation
Strings and Serialization
Fundamentals of Programming I More Data Modeling
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Topics Introduction to File Input and Output
Bryan Burlingame 17 April 2019
CSE 231 Lab 5.
Introduction to Programming
Topics Introduction to File Input and Output
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Python Reserved Words Poster
Lecture 3 - Instruction Set - Al
Presentation transcript:

Computer Science 111 Fundamentals of Programming I Persistent Data Models Object Serialization

Helper Function to Create a Bank from bank import Bank def createBank(numAccounts = 1): """Returns a new bank with the given number of accounts.""" bank = Bank() upperPin = numAccounts + 1000 for pinNumber in range(1000, upperPin): bank.add(SavingsAccount('Ken', str(pinNumber))) return bank bank = createBank(5) # Creates 5 accounts in bank

Transience and Persistence Data in computer memory are transient and are lost when the program quits Data become persistent when they can be saved to a file and reloaded from a file save Data model File storage load

Saving a Savings Account Include a method for writing an account’s info to a text file: def save(self, fileObj): # In SavingsAccount fileObj.write(self.name + '\n') fileObj.write(self.pin + '\n') fileObj.write(str(self.balance) + '\n') >>> a = SavingsAccount('Ken', '8809', 500.00) >>> fileObj = open('account.txt', 'w') >>> a.save(fileObj) >>> fileObj.close() Run the method in the shell and then inspect the file:

Saving an Entire Bank Include a method for writing a bank’s info to a text file: def save(self, fileName): # In Bank fileObj = open(fileName, 'w') for account in self.accounts.values(): account.save(fileObj) fileObj.close() >>> bank = createBank(5) >>> bank.save('bank.txt') Run the method in the shell and then inspect the file:

Class Methods vs Instance Methods Define a class method and an instance method: class MyClass: def instanceMethod(self): return 'I am an instance method.' @classmethod def classMethod(cls): return 'I am a class method.' >>> print(MyClass.classMethod()) I am a class method. >>> obj = MyClass() >>> print(obj.instanceMethod()) I am an instance method. Try both methods in the shell:

Class Methods vs Instance Methods Like a class variable, a class method is used with the class’s name An instance method is always used with an instance Class methods can see class variables but not instance variables Instance methods can see both kinds of variables >>> print(MyClass.classMethod()) I am a class method. >>> print(obj.instanceMethod()) I am an instance method.

Why Use Class Methods? Class methods are often used to create and return instances of those classes Such methods are also called factory methods >>> class MyClass: @classmethod def getInstance(cls): return MyClass() >>> obj = MyClass.getInstance() Example:

Loading a Savings Account Include a class method to read an account’s info from a text file and return a new instance with that info: @classmethod def load(cls, fileObj): # In SavingsAccount name = fileObj.readline().strip() pin = fileObj.readline().strip() balance = fileObj.readline().strip() if not name: return None else: return SavingsAccount(name, pin, float(balance)) >>> fileObj = open('account.txt', 'r') >>> a = SavingsAccount.load(fileObj) >>> print(a) Run the method in the shell and then inspect the account:

Loading an Entire Bank Include a class method to load accounts and create a bank: @classmethod def load(cls, fileName): # In Bank fileObj = open(fileName, 'r') bank = Bank() while True: a = SavingsAccount.load(fileObj) if not a: break else: bank.addAccount(a) fileObj.close() return bank >>> bank = Bank.load('bank.txt') >>> print(bank) Test the method in the shell and then inspect the account:

Problems Lots of manual labor to output and input the attributes of accounts as text Must change this code every time we modify the structure of an account (add an address attribute, etc.) A text file is insecure and inefficient

Solution: Pickle the Data Pickling automates the process of converting an object to a form suitable for file storage Unpickling automates the process of converting data from file storage back to the appropriate objects pickling Data model File storage unpickling

The pickle Module dump(obj, fileObj) # Pickles obj and writes it to fileObj load(fileObj) # Reads an object from fileObj, # unpickles it, and returns it # Raises an exception if the end of # the file is reached

Using pickle for Output >>> import pickle >>> fileObj = open('test.dat', 'wb') >>> pickle.dump('Hi there!', fileObj) >>> fileobj.close() Must use the argument “wb” or “rb” when opening a file for output or input The “b” stands for “byte”

Using pickle for Input >>> import pickle >>> fileObj = open('test.dat', 'wb') >>> pickle.dump('Hi there!', fileObj) >>> fileobj.close() >>> fileObj = open('test.dat', 'rb') >>> s = pickle.load(fileObj) >>> print(s) Hi there!

Using pickle with Accounts >>> import pickle >>> fileObj = open('test.dat', 'wb') >>> account = SavingsAccount('Ken', '8809', 500.00) >>> pickle.dump(account, fileObj) >>> fileobj.close() >>> fileObj = open('test.dat', 'rb') >>> account = pickle.load(fileObj) >>> print(account) Blah blah blah

Saving an Entire Bank (Text) Include a method for writing an bank’s info to a text file: def save(self, fileName): # In Bank fileObj = open(fileName, 'w') for account in self.accounts.values(): account.save(fileObj) fileObj.close() Run the method in the shell and then inspect the file: >>> bank = createBank(5) >>> bank.save('bank.txt')

Saving an Entire Bank (Pickled) Include a method for writing an bank’s info to a text file: def save(self, fileName): # In Bank fileObj = open(fileName, 'wb') for account in self.accounts.values(): pickle.dump(account, fileObj) fileObj.close() Run the method in the shell and then inspect the file: >>> bank = createBank(5) >>> bank.save('bank.dat')

Loading an Entire Bank (Text) Include a class method to load accounts and create a bank: @classmethod def load(cls, fileName): # In Bank fileObj = open(fileName, 'r') bank = Bank() while True: a = SavingsAccount.load(fileObj)) if not a: break else: bank.addAccount(a) fileObj.close() return bank >>> bank = Bank.load('bank.txt') >>> print(bank) Test the method in the shell and then inspect the account:

Loading an Entire Bank (Pickled) Include a class method to load accounts and create a bank: @classmethod def load(cls, fileName): # In Bank fileObj = open(fileName, 'rb') bank = Bank() try: while True: a = pickle.load(fileObj) bank.addAccount(a) except Exception(e): fileObj.close() return bank Test the method in the shell and then inspect the account: >>> bank = Bank.load('bank.dat') >>> print(bank)

For Wednesday Search algorithms