

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


# GettersandSetters.py
# Define class BankAccount class BankAccount: # Initialize balance to 0 def init(self, name, balance = 0.0): self.log("Account created!") self.name = name self.balance = balance
def getBalance(self): #Getter for balance self.log("Balance checked at " + str(self.balance)) return self.balance
def setBalance(self, newBalance): #Setter for balance self.log("Balance changed to " + str(newBalance)) self.balance = newBalance
def log(self, message): #Logging method myLog = open("Log.txt", "a") print(message, file = myLog) myLog.close()
myBankAccount = BankAccount("David Joyner") myBankAccount.setBalance(20.0) print(myBankAccount.getBalance())
# ======================================
# BANKING OPERATIONS - ACCOUNT BALANCE LOG
# ======================================
# EncapsulatingOtherFunctions.py
class BankAccount: def init(self, name, balance = 0.0):
self.log("Account created!") self.name = name self.balance = balance
def getBalance(self): self.log("Balance checked at " + str(self.balance)) return self.balance
def deposit(self, amount): self.balance += amount self.log("+" + str(amount) + ": " + str(self.balance))
def withdraw(self, amount): self.balance -= amount self.log("-" + str(amount) + ": " + str(self.balance))
def log(self, message): myLog = open("Log.txt", "a") print(message, file = myLog) myLog.close()
myBankAccount = BankAccount("David Joyner") myBankAccount.deposit(20.0) print(myBankAccount.getBalance()) myBankAccount.withdraw(10.0) print(myBankAccount.getBalance())
The key insight on getters and setters — they are much simpler than you were making them:
Getters just return the value, nothing else Setters just = assign the new value, nothing else