Today we talk about Python classes. So far we've written programs that are just made up of functions. Today we introduce the Python class, a mechanism to group together related functions and the variables that these functions share in common. Classes are a common programming paradigm in many languages, but Python has its own flavor of implementation.
You've already been using instances of classes without realizing it. The List is a class, as well as a Dictionary. When you create a List and append to it, you do this:
nums = list()
nums.append(5)
nums.append(9)
...you've created an instance of a class. Your nums variable is what we call an object, one instance of the class list. The append() function is actually defined in the list class which is why we use the .append() notation with your nums variable, instead of just calling append() by itself. The following doesn't make sense, right?
nums = list()
append(5) # append to what? You need an object 'nums' to append to!
Today's topic is the last major programming concept in this course, and it is a very important topic to the rest of the semester.
Read Chapter 14 up to and including "Classes as Types".
class BankAccount:
def __init__(self, owner, starting):
self.owner = owner
self.amt = starting
self.fee = 1 # every withdrawal will have a $1 penalty fee
def deposit(self, dollars):
self.amt += dollars
def withdraw(self, dollars):
self.amt -= dollars
self.amt -= self.fee
def balance(self):
return self.amt
# Create the account.
name = input("What's your name? ")
acct = BankAccount(name, 0)
# User input:
# 'deposit 1000'
# 'withdraw 500'
# 'balance'
# 'exit'
command = input("Action: ")
while command != 'exit':
if command.startswith('deposit'): # "deposit 400"
action,amt = command.split()
acct.deposit(int(amt))
elif command.startswith('withdraw'): # "withdraw 200"
action,amt = command.split()
acct.withdraw(int(amt))
elif command == 'balance': # "balance"
print('Your balance is', acct.balance())
command = input("Action: ")
print('Goodbye', acct.owner, 'your final balance is', acct.amt)