def forecast(bank, years):
class Bank:
def __init__(self, name):
self.name = name
self.mark_cap = 0
self.acc_list = []
self.age = 0
def lend(self, principal, ann_inc):
self.mark_cap -= principal
def forward_year(self):
self.age += 1
def back_year(self):
if self.age == 0:
self.age = 0
self.age -= 1
def show_high(self):
print(Bank.acc_list[0])
class Account:
def __init__(self, ID, password):
self.ID = ID
self.password = password
if len(password) < 5:
print('Password must be at least 5 characters')
self.amount = 0
self.interest = 0.0175
self.acc_org = [ID, password, self.amount, self.interest]
def deposit(self, x):
self.amount += x
self.acc_org[2] = self.amount
def withdraw(self, y):
self.amount -= y
self.acc_org[2] = self.amount
def threshold(self):
if self.amount >= 1000000:
self.interest = 0.02
def comp_int(self, n):
self.threshold()
self.amount *= (1 + self.interest)**n
self.acc_org[2] = self.amount
def show_amount(self):
print(self.amount)
def add_2_bank(self, name):
bank_name = name
bank_name.acc_list.append(self.acc_org)
X = Bank('Bank of china')
Account1 = Account('12345', '12345')
Account1.deposit(200)
Account1.comp_int(2)
Account1.add_2_bank(X)
X.show_high()
The error that I am getting is that my 'Bank' object (X) has no attribute acc_list(). Someone please help me.
In the show_high method, modify Bank.acc_list to self.acc_list. Only static properties can be used like Bank.*.
Related
So I'm just doing a learning project and I need some help.
class Car:
def __init__(self):
self.speed = 0
self.color = ""
self.weight = 0
self.engine = 4
self.name = ""
self.mpg = 25
self.maintenanceLog = []
self.oilChanges = []
#mutator methods
def setSpeed(self, sp):
self.speed = sp
def setColor(self, cl):
self.color = cl
def setWeight(self, w):
self.weight = w
def setEngine(self, e):
self.engine = e
def setName(self, n):
self.name = n
def setMpg(self, mpg):
self.mpg = mpg
def addOilChange(self, oc):
self.oilChanges.append(oc)
def addMaintenance(self, ml):
self.maintenanceLog.append(ml)
#accessor methods
def getSpeed(self):
return self.speed
def getColor(self):
return self.color
def getWeight(self):
return self.weight
def getEngine(self):
return self.engine
def getName(self):
return self.name
def getMPG(self):
return self.mpg
def getAllOilChanges(self):
print("")
print("----------OIL CHANGES----------")
for oc in self.oilChanges:
print(oc)
def getMaintenanceLogs(self):
print("")
print("----------MAINTENANCE LOGS----------")
for ml in self.maintenanceLog:
print(ml)
def setInfo(car):
car.setSpeed(int(input(f"Speed of {car}")))
car.setWeight(int(input(f"Weight of {car}")))
car.setName(input(f"Name of {car}"))
car.setColor(input(f"Color of {car}"))
car.setEngine(int(input(f"Engine of {car}")))
car.setMpg(int(input(f"Miles per Gallon of {car}")))
def getInfo(car):
print(f"Speed of {car} is {car.getSpeed()} mph.")
print(f"Weight of {car} is {car.getWeight()} pounds.")
print(f"Name of {car} is {car.getName()}.")
print(f"Color of {car} is {car.getColor()}.")
print(f"Engine cylinders of {car} are {car.getEngine()}.")
print(f"Miles per Gallon of {car} is {car.getMPG()}.")
def main():
carList = []
Object1= Car()
carList.append(Object1)
print(carList)
for obj in carList:
setInfo(obj)
getInfo(obj)
main()
Thats's the code, now, whenever I run it, I want to get asked Speed of Object1:
Instead, I get asked Speed of <main.Car object at 0x0000024B093CEFD0>:
How can I see the name of the object instead of that hash value... I want to keep adding objects with the class Car and then pass them through a loop to fill in the information regarding the object, but if the list of objects was [Object 1, Object 2, Object 3... Object N] I want it to refer to that name (Object 1) instead of <main.Car object at 0x0000024B093CEFD0>
You can pass the name to use in the prompts as an argument to setInfo().
def setInfo(car, name=None):
if name is None:
name = car.name
car.setSpeed(int(input(f"Speed of {name}")))
car.setWeight(int(input(f"Weight of {name}")))
car.setName(input(f"Name of {name}"))
car.setColor(input(f"Color of {name}"))
car.setEngine(int(input(f"Engine of {name}")))
car.setMpg(int(input(f"Miles per Gallon of {name}")))
and then use that in the loop.
for i, obj in enumerate(carList, 1):
setInfo(obj, f"Object {i}")
getInfo(obj)
I am working on a python project. All was working well when I just had one level of inheritance but once I added SavingAccount and CheckingAccount which should be a child of BankAccount which is a child of Customer I started to get the following error: 'CheckingAccount' object has no attribute 'balance'
I assumed I would do the second layer of inheritance the same as the first but maybe I must be missing. Thanks in advance for any help!
class Customer:
def __init__(self,firstName, lastName, social):
self.firstName = firstName
self.lastName = lastName
self.social = social
def setfirstName(self,firstName):
self.firstName = firstName
def setlastName(self,lastName):
self.lastName = lastName
def __str__(self):
self.name = "{},{} (SSN:{})".format(self.firstName, self.lastName,self.social)
return self.name
class BankAccount(Customer):
from random import randint
n = 10
range_start = 10**(n-1)
range_end = (10**n)-1
accountNumber = randint(range_start, range_end)
def __init__(self,customer,balance = 0):
self.customer = customer
self.balance = balance
def setCustomer(self,customer,accountNumber):
self.customer = customer
self.accountNumber = accountNumber
def getCustomer(self,customer,accountNumber):
return self.customer, self.accountNumber
def deposit(self, amount):
self.balance = self.balance + amount
return self.balance
def withdrawal(self, amount):
self.balance = self.balance - amount
return self.balance
def __str__(self):
customer = "{} account number: {}, balance: ${}".format(self.customer,self.accountNumber,self.balance)
return customer
class CheckingAccount(BankAccount):
def __init__(self, bankAccount):
self.bankAccount = bankAccount
def applyAnnualInterest(self):
excess = self.balance - 10000
if excess > 0:
interest = (excess * .02)
self.balance = self.balance + interest
return self.balance
else:
return self.balance
class SavingAccount(BankAccount):
def __init__(self, bankAccount):
self.bankAccount = bankAccount
def applyAnnualInterest(self):
interest = (self.balance * .05)
self.balance = self.balance + interest
return self.balance
def main():
alin = Customer('Alin', 'Smith', '111-11-1111')
mary = Customer('Mary', 'Lee', '222-22-2222')
alinAccnt = CheckingAccount(alin)
maryAccnt = SavingAccount(mary)
alinAccnt.deposit(20000)
print(alinAccnt)
You need to initialise the parent; try:
class CheckingAccount(BankAccount):
def __init__(self, bankAccount):
super(CheckingAccount, self).__init__()
self.bankAccount = bankAccount
Don't forget the intermediate class too!
class BankAccount(Customer):
def __init__(self,customer,balance = 0):
super(BankAccount, self).__init__()
self.customer = customer
self.balance = balance
This will ensure the parent constructors get called too.
I have defined following class of a bank account. The account should always start with 0.0 balance. How can I enforce that the value is always set 0.0 even if the user set it differently at the initiation?
class Account(object):
def __init__(self, name, balance=0.0):
self.name = name
self.balance = balance
def add_money(self, deposit_amnt):
self.balance += deposit_amnt
def withdraw_money(self, withdraw_amnt):
if withdraw_amnt > self.balance:
raise ValueError('Withdraw amount is more than balance')
else:
self.balance -= withdraw_amnt
def check_balance(self):
return self.balance
my_account = Account('Tim', 15)
my_account.check_balance()
>>> 15
You can ommit balance in __init__ if you want to start with 0. You have add method to do that later.
def __init__(self, name):
self.name = name
self.balance = 0
I have a class where I'm expecting this:
print(rithesh.amount) = 150.
How can I do this?
Here is my code:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
def add_amount(self, amount):
self.amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
You can declare your amount variable in your __init__ method as 0. Then make a small change in your add_amount method.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
output
150
The actual way of having properties in python is by using #property decorator
for example, in your class:
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
#property
def add_amount(self):
return self.add_amount
#add_amount.setter
def add_amount(self, amount):
self.add_amount = amount
rithesh = Customer("Rithesh", "8896398598", "ritheshb1#gmail.com")
rithesh.add_amount = 150
print(rithesh.add_amount)
Got how to do it.
i have to declare the value self.amount = 0 during initialization.
class Customer:
total_amount = 0
def __init__(self, name, mob, email, amount=None):
self.name = name
self.mob = mob
self.eamil = email
self.amount = 0
def add_amount(self, amount):
self.amount += amount
rithesh = Customer("Ritehsh", "8892398598", "ritheshb1#gmail.com")
rithesh.add_amount(100)
rithesh.add_amount(50)
print(rithesh.amount)
hence getting output as print(rithesh.amount) = 150
What is happening is that when you call add_amount you are not adding the value to self.amount you are just setting it.
Just change the definition of add_amount from:
self.amount = amount
to:
self.amount += amount
And add to the __init__ method:
self.amount = 0
I keep getting this error:
<__main__.product object at 0x0231A7B0>
from the code:
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlist(self):
x = ''
for i in self.cartlist:
x = i, "/n"
return x
instead of executing the function prntlist it displays that error
full code:
class product(object):
name = ''
price = 0
def __init__(self, name, price):
self.name = name
self.price = price
def prnt(self):
print("\n**********************************************************")
print("Item\t\t\t Price")
print(self.name,"............ $", self.price)
print("\n**********************************************************")
def prntline(self):
x = self.name + ".........." + self.price
return x
class cart(object):
totalprice = 0
cartlist = []
def __init__(self):
self.totalprice = totalprice
self.cartlist = []
def setprice(self):
totprice = self.totalprice
for i in self.cartlist:
self.totalprice += i.price
return totprice
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlinecart(self):
print("You have purchased: ", self.prntlist())
def prntlist(self):
x = ''
for i in self.cartlist:
x = i, "/n"
return x
def additem(self, item):
self.cartlist.append(item)
print("Ah, fresh out. But we can have it shipped to your house next week")
Ok, I made your example work for me, just to see what is happening:
class product(object):
name = ''
price = 0
def __init__(self, name, price):
self.name = name
self.price = price
def prnt(self):
print("\n**********************************************************")
print("Item\t\t\t Price")
print(self.name,"............ $", self.price)
print("\n**********************************************************")
def prntline(self):
x = self.name + ".........." + self.price
return x
class cart(object):
totalprice = 0
cartlist = []
def __init__(self):
self.totalprice = 0
self.cartlist = []
def setprice(self):
totprice = self.totalprice
for i in self.cartlist:
self.totalprice += i.price
return totprice
def prnt(self):
print("\n**********************************************************")
print(self.prntlist())
print("Grand total\t\t\t\t$", self.setprice())
print("**********************************************************\n")
def prntlinecart(self):
print("You have purchased: ", self.prntlist())
def prntlist(self):
x = ''
print('fff')
for i in self.cartlist:
x = i, "/n"
return x
def additem(self, item):
self.cartlist.append(item)
print("Ah, fresh out. But we can have it shipped to your house next week")
mycart = cart()
RL = product("Red Leicester", 13.99)
RL.prnt()
mycart.additem(RL)
mycart.prnt()
The output is:
**********************************************************
Item Price
Red Leicester ............ $ 13.99
**********************************************************
Ah, fresh out. But we can have it shipped to your house next week
**********************************************************
fff
(<__main__.product object at 0x7ffbe52609e8>, '/n')
Grand total $ 0
**********************************************************
It seems that you ask about this: <__main__.product object at 0x7ffbe52609e8>. As I wrote in the first comment, this is because you are making tuple, not a string when with the following line x = i, "/n".