Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.

Similar presentations


Presentation on theme: "CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn."— Presentation transcript:

1 CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn

2 Quick Info Dr. Curry Guinn –CIS 2045 –guinnc@uncw.eduguinnc@uncw.edu –www.uncw.edu/people/guinnc –962-7937 –Office Hours: MWR: 11:00am-12:00pm and by appointment –Teaching Assistant: Paul Murray (Hours TBD)

3 Today Reminder about tonight’s Blackboard quiz Homework 1 due tonight Homework 2 assigned (due next week) Python I/O  Input/Output Python functions Object-Oriented Programming (Classes, objects, methods, constructors)

4 Homework due Thursday Call your program ComputeAverage –Read in a file (called “numbers.txt”) of integers and compute and print the average –Also, compute and print the average of just the non-negative numbers. –Find and print the minimum –Find and print the maximum

5 One way to solve it …. Read the numbers in but don’t save them all in a list. Do the calculations “on the fly”

6 Another way to solve it …. Read the numbers into a list Then, –Do the calculations on the list Better?

7 7 Working with Files To read a file: >>> for line in open('corpus.txt', 'r').readlines()... print line To write to a file: >>> outfile = open('output.txt', 'w') >>> outfile.write(my_string) >>> outfile.close() Example: >>> outfile = open('output.txt', 'w') >>> for line in open('corpus.txt', 'r').readlines():... outfile.write(line.replace('a', 'some')) >>> outfile.close()

8 A really, really useful string method: split tokens = line.split() Will take a string like “Mary Jones 300.00” and produce a list (tokens, in this case) that looks like: [“Mary”, “Jones”, “300.00”]

9 Another really useful string method strip() It removes white space from the beginning and end of a string s = “ hello “ t = s.strip() –Now, t is “hello”

10 10 Functions A function is a reusable part of a program. Functions are defined with def >>> def square(x):... return x*x >>> print square(8) 64 Optional arguments: >>> def power(x, exp=2): # exp defaults to 2... if x <= 0: return 1... else: return x*power(x, exp-1)

11 The Basics of Object- Oriented Programming in Python

12 First, a little history and motivation

13 The “Old” Style of Programming: Procedural Abstractions Define tasks to be performed –Verb-oriented Break tasks into smaller and smaller pieces –Until you reach an implementable size Define the data to be manipulated Design how functions interact –What's the input –What's the output Group functions into components (“modules" or "classes") Write the code

14 Object-oriented programming First goal: Model the objects of the world –Noun-oriented –Focus on the domain of the program Phases –Object-oriented analysis: Understand the domain Define an object-based model of it –Object-oriented design: Define an implementation Design the solution –Object-oriented programming: Build it

15 Defining an object Objects know things. Data that is internal to the object. We often call those instance variables. Objects can do things. Behavior that is internal to the object. We call functions that are specific to an object methods. We access both of these using dot notation object.variable object.method()

16 Classes Objects are instances of classes in many object-oriented languages. –Including Smalltalk, Java, JavaScript, C++, Objective-C, and Python. A class defines the data and behavior of an object. –A class defines what all instances of that class know and can do.

17 Working with classes in Python Defining a class Constructors Instance variables Methods

18 My favorite example: Bank Accounts Everybody has a bank account All of those bank accounts have similar features However, each particular instance of a bank account is different? –How?

19 Classes and objects A class is an abstract definition of an object. –It defines similar data and methods shared by all object’s of that class An object is an instance of a class. –The instantiation of a class is the process of creating a new object.

20 Defining a class in Python class BankAccount: Inside of this class definition are the methods for manipulating the data in the class.

21 The constructor for a class The most important “method” for a class is its constructor. The constructor tells how to create a particular instance of a class. It has a very definite syntax that is required in Python.

22 Constructor class BankAccount: def __init__(self, startingBalance, name): self.balance = startingBalance self.name = name account1 = BankAccount(100, "Jane Doe") account2 = BankAccount(3000, "Mary Smith") print(account1, account2)

23 Things to notice about constructors self is ALWAYS the first parameter to __init__ In fact, self is ALWAYS the first parameter to any instance method in a class. To refer to instance variables, the name of the variable must ALWAYS be prefixed with “self.”

24 I don’t like how it’s printing I’ll override the built-in __str__ method which tells how to print the object. def __str__(self): return self.name + "\t" + str(self.balance)

25 What other methods might be good for a BankAccount? def deposit(self, amt): self.balance += amt def withdraw(self, amt): self.balance -= amt account1 = BankAccount(100, "Jane Doe") account2 = BankAccount(3000, "Mary Smith") print(account1) print(account2) account1.deposit(75.25) account2.withdraw(317.18) print(account1) print(account2)

26 More on Bank Account Methods that return values Write calculateInterest such that it returns 0.015 times the balance. Test it!

27 Making a list of BankAccounts Create a loop that iterates 100 times. Inside of the loop, create a bank account object and add it to a list. Now, iterate through the list, printing out each bank account.

28 Making random accounts Here is a list of common first names: FirstNames.txt FirstNames.txt Here is a list of common last names: LastNames.txt LastNames.txt Let’s randomly select a first name and a last name to create a random person. Also, we’ll randomly generate a bank account balance Now, write this to a file called “accounts.txt”.


Download ppt "CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn."

Similar presentations


Ads by Google