a259e9ce6ae534b37f0b9e2eed1b33ca.ppt
- Количество слайдов: 21
Computer Science 111 Fundamentals of Programming I Persistent Data Models Object Serialization
Helper Function to Create a Bank from bank import Bank def create. Bank(num. Accounts = 1): """Returns a new bank with the given number of accounts. """ bank = Bank() upper. Pin = num. Accounts + 1000 for pin. Number in range(1000, upper. Pin): bank. add(Savings. Account('Ken', str(pin. Number))) return bank = create. Bank(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 load File storage
Saving a Savings Account Include a method for writing an account’s info to a text file: def save(self, file. Obj): # In Savings. Account file. Obj. write(self. name + 'n') file. Obj. write(self. pin + 'n') file. Obj. write(str(self. balance) + 'n') Run the method in the shell and then inspect the file: >>> a = Savings. Account('Ken', '8809', 500. 00) >>> file. Obj = open('account. txt', 'w') >>> a. save(file. Obj) >>> file. Obj. close()
Saving an Entire Bank Include a method for writing a bank’s info to a text file: def save(self, file. Name): # In Bank file. Obj = open(file. Name, 'w') for account in self. accounts. values(): account. save(file. Obj) file. Obj. close() Run the method in the shell and then inspect the file: >>> bank = create. Bank(5) >>> bank. save('bank. txt')
Class Methods vs Instance Methods Define a class method an instance method: class My. Class: def instance. Method(self): return 'I am an instance method. ' @classmethod def class. Method(cls): return 'I am a class method. ' Try both methods in the shell: >>> print(My. Class. class. Method()) I am a class method. >>> obj = My. Class() >>> print(obj. instance. Method()) I am an instance method.
Class Methods vs Instance Methods • Like a class variable, a class method is used with the class’s name >>> print(My. Class. class. Method()) I am a class method. • An instance method is always used with an instance >>> print(obj. instance. Method()) I am an instance method. • Class methods can see class variables but not instance variables • Instance methods can see both kinds of variables
Why Use Class Methods? • Class methods are often used to create and return instances of those classes • Such methods are also called factory methods Example: >>> class My. Class: @classmethod def get. Instance(cls): return My. Class() >>> obj = My. Class. get. Instance()
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, file. Obj): # In Savings. Account """Creates and returns an account from a text file. """ name = file. Obj. readline(). strip() pin = file. Obj. readline(). strip() balance = file. Obj. readline(). strip() if not name: return None else: return Savings. Account(name, pin, float(balance)) Run the method in the shell and then inspect the account: >>> file. Obj = open('account. txt', 'r') >>> a = Savings. Account. load(file. Obj) >>> print(a)
Loading an Entire Bank Include a class method to load accounts and create a bank: @classmethod def load(cls, file. Name): # In Bank """Creates and returns a bank from a text file. """ file. Obj = open(file. Name, 'r') bank = Bank() while True: a = Savings. Account. load(file. Obj) if not a: break else: bank. add(a) file. Obj. close() return bank Test the method in the shell and then inspect the account: >>> bank = Bank. load('bank. txt') >>> print(bank)
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 unpickling File storage
The pickle Module dump(obj, file. Obj) # Pickles obj and writes it to file. Obj load(file. Obj) # Reads an object from file. Obj, # unpickles it, and returns it # Raises an exception if the end of # the file is reached
Using pickle for Output >>> import pickle >>> file. Obj = open('test. dat', 'wb') >>> pickle. dump('Hi there!', file. Obj) >>> 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 >>> file. Obj = open('test. dat', 'wb') >>> pickle. dump('Hi there!', file. Obj) >>> fileobj. close() >>> file. Obj = open('test. dat', 'rb') >>> s = pickle. load(file. Obj) >>> print(s) Hi there!
Using pickle with Accounts >>> import pickle >>> file. Obj = open('test. dat', 'wb') >>> account = Savings. Account('Ken', '8809', 500. 00) >>> pickle. dump(account, file. Obj) >>> fileobj. close() >>> file. Obj = open('test. dat', 'rb') >>> account = pickle. load(file. Obj) >>> print(account) Blah blah
Saving an Entire Bank (Text) Include a method for writing an bank’s info to a text file: def save(self, file. Name): # In Bank file. Obj = open(file. Name, 'w') for account in self. accounts. values(): account. save(file. Obj) file. Obj. close() Run the method in the shell and then inspect the file: >>> bank = create. Bank(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, file. Name): # In Bank file. Obj = open(file. Name, 'wb') for account in self. accounts. values(): pickle. dump(account, file. Obj) file. Obj. close() Run the method in the shell and then inspect the file: >>> bank = create. Bank(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, file. Name): # In Bank file. Obj = open(file. Name, 'r') bank = Bank() while True: a = Savings. Account. load(file. Obj)) if not a: break else: bank. add(a) file. Obj. close() return bank Test the method in the shell and then inspect the account: >>> bank = Bank. load('bank. txt') >>> print(bank)
Loading an Entire Bank (Pickled) Include a class method to load accounts and create a bank: @classmethod def load(cls, file. Name): # In Bank file. Obj = open(file. Name, 'rb') bank = Bank() try: while True: a = pickle. load(file. Obj) bank. add(a) except Exception(e): file. Obj. 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