Advertisement
here2share

# a typical Python class example

Aug 10th, 2016
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. # a typical Python class example
  2. # newer class convention uses inheritance place holder (object)
  3.  
  4. class Account(object):
  5.     # __init__() initializes a newly created class instance,
  6.     # 'self' refers to the particular class instance
  7.     # and also carries the data between the methods.
  8.     # You have to supply the initial account balance
  9.     # during creation of the class instance.
  10.     def __init__(self, initial):
  11.         self.balance = initial
  12.  
  13.     def deposit(self, amt):
  14.         # a function within a class is called a method
  15.         # self always starts the argument list of a method
  16.         self.balance = self.balance + amt
  17.  
  18.     def withdraw(self,amt):
  19.         self.balance = self.balance - amt
  20.        
  21.     def getbalance(self):
  22.         return self.balance
  23.  
  24.  
  25. # create two new class instance, Mary's and Tom's account
  26. mary = Account(1000.00) # start with initial balance of 1000.00
  27. tom = Account(3000.00)  # tom is lucky he starts with 3000.00
  28.  
  29. # Mary makes deposits and a withdrawel
  30. mary.deposit(500.00)
  31. mary.deposit(23.45)
  32. mary.withdraw(78.20)
  33.  
  34. # Tom also accesses his account
  35. tom.withdraw(1295.50)
  36.  
  37. # now look a the account balances
  38. print "Mary's balance = $%0.2f" % mary.getbalance()  # $1445.25
  39. print "Tom's balance  = $%0.2f" % tom.getbalance()   # $1704.50
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement