Classes, Objects and Methods in Python

Download Report

Transcript Classes, Objects and Methods in Python

CSC 231: Introduction to
Data Structures
Python and Objects
Dr. Curry Guinn
Quick Info
• Dr. Curry Guinn
– CIS 2045
– [email protected]
– www.uncw.edu/people/guinnc
– 962-7937
– Office Hours: MTWR: 11:00am-12:00pm
and by appointment
– Teaching Assistant: Paul Murray (Hours TBD)
Today
•
•
•
•
Reminder about Tuesday’s Blackboard quiz
And Homework 1 is due Tuesday too
Python Basics
Object-Oriented Programming (Classes, objects,
methods, constructors)
Lab/Homework 1assignment
• Call your program ComputeAverage
– Read in a file (called “numbers.txt”) of integers and
compute some stats
– Find and print the average
– Find and print the minimum
– Find and print the maximum
– Compute and print the median
– Don’t use any of the built-in statistics methods like
min, max, or sum. You can use sort to compute the
median.
• Submit this program on Blackboard under the
appropriate link
One way to solve it ….
• Read the numbers in but don’t save them
all in a list.
• Do the calculations “on the fly”
– Except this is really impossible with
calculating the median
Another way to solve it ….
• Read the numbers into a list
• Then,
– Do the calculations on the list
• Better?
Useful things for Homework 1
input = open("numbers.txt", "r")
for line in input:
x = int(line)
The Guided Lab of Today’s
Python Review
1. Turn and face your computer
2. Start PyCharm
3. Under Tools menu, select
– Run Python Console
4. Let’s try a few simple things to make sure
we understand how to work in the
interpreter
Some simple interpreter
interactions
• Do some math
– What is 2 + 2?
– What is 10 / 3? What if I want integer
division?
– 10//3
– How do I compute 210?
– How do I take log2(1024)?
– What does import do?
• What is the difference between “import math” and
“from math import *”?
Some simple assignment and
strings at the interpreter
• Assign a variable to a string
• Find the length of the string
• What is the 4th character?
– Don’t forget that indices start at 0. What is the
index of the 4th character?
• Determine the substring of length 3 that
starts at index 1.
• Is “cat” inside of your string?
• Does your string start with “a”?
Creating and Interpreting a
Python file inside PyCharm
• Under File – select New Project.
• Give your project a name in the dialog
box.
– Notice that dialog box tells you where the
project will be placed on your computer
– You can change that if you want
• Perhaps make it your flash drive
• Or your timmy drive  Preferred
– All user files are periodically deleted from
these lab machines (essentially, every time
it reboorts)
Creating a .py file
• In the Project pane, right click on your project name and
choose New Python file.
– Give it a name
– You do not need to add the .py extension
• It will do it automatically
• In the editor window that pops up, type in some python
code
• Save by clicking on the archaic floppy disk icon
• Run – Run
– And then select which file you want to run
Running at the console
• In windows explorer, navigate to the folder that
contains your newly created .py file.
– If you have forgotten where it is, look at the
title bar of PyCharm
• In explorer, shift-RightClick on the folder and
select “Open Command Window Here”.
• Now type “python test.py” or if that doesn’t work
• C:\python34\python test.py
PyCharm is drop-and-drag
• You can drag files into your Python
projects
• And also copy them out of those projects
Let’s do something complicated
• Generate a file (called “numbers.txt”)
containing somewhere between 500 and
1000 random integers between -100 and
100, inclusive.
• Useful:
–
–
–
–
–
–
import random
howMany = random.randrange(500, 1001)
number = random.randrange(-100, 101)
outputfile = open("numbers.txt", "w")
for count in range(0, howMany):
outputfile.write("%s\n" % number)
Working with classes in Python
•
•
•
•
Defining a class
Constructors
Instance variables
Methods
Let’s do some more stuff in
PyCharm
1. Create a new Python file called
BankAccount.
2. Make the class definition.
3. Define the constructor.
4. Re-define __str__
5. Define methods deposit and withdraw
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?
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.
Defining a class in Python
class BankAccount:
Inside of this class definition are the
methods for manipulating the data in the
class.
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.
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)
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.”
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)
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)
More on Bank Account
• Methods that return values
• Write calculateInterest such that it returns
0.015 times the balance.
• Test it!
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.
Making random accounts
• Here is a list of common first names:
FirstNames.txt
• Here is a list of common last names:
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”.
Using a Second File
• Create another file, ProcessAccounts.
• At the top put
from BankAccount import *
• Now have your program open the file
accounts.txt
• Read in all the bank accounts, creating a
corresponding BankAccount object and
putting it in a list
Next Tuesday
• More object-oriented programming
• Quiz 1 due Tuesday night
• So is Homework 1!!!
• Quiz 2 due Thursday night