Manipulating items of array of class objects in Python - python

For the code below, I create an array of class objects using a for loop. However, I'm not able to access and modify the objects in the list. What do I have to change to make this work?
def main():
class BankAccount:
def __init__(self,nameOfCustomer,balanceOfCustomer):
self.name = nameOfCustomer
self.balance = balanceOfCustomer
print "\nNew customer created in system with name " + self.name + " and initial balance of $" + str(self.balance)
def get_balance(self):
print "The current balance for " + self.name + " is: $" + str(self.balance)
return self.balance
def deposit(self,amount):
self.balance += amount
print self.name + " just deposited $" + str(amount)
return self.balance
def withdraw(self,amount):
self.balance -= amount
print self.name + " just withdrew $" + str(amount)
return self.balance
customerList = {"Eric": 10000,
"Tom": 20000,
"Bill": 25000,
"Casey": 40000}
individualAccountList = []
for key, value in customerList.iteritems():
individualAccountList.append(BankAccount(key,customerList[key]))
for i in individualAccountList:
print i
if __name__ == '__main__':
main()

it works:
for i in individualAccountList:
print i.name
gives:
Casey
Bill
Eric
Tom
than:
individualAccountList[0].name = "name changed"
print individualAccountList[0].name
>> name changed

Related

What do we need to do to fix this equation so that it works in our Python code?

Assignment and code below...
I am assisting my son with his homework. I know coding, but not Python. He has gotten this far and has asked me to jump in to assist and I am stumped. I believe that the equation for the total take-home salary is too long, but I am not sure what to do to help. The code works as is, but when we try to switch the "...will take home $" + str(emp_1.salary) + ", after taxes." with "...will take home $" + str(emp_1.apply_taxes()) + ", after taxes." for both emp_1 and emp_2 we get an error that apply_taxes is not defined. all we need to do is get the equation to work and we will be good. Any suggestions would be greatly appreciated!
Thank you!!
This is the assignment:
Include to class variables that will account for the federal tax rate (0.2) and the state tax rate (0.0314)
Using these variables, add a method to the init method that will deduct BOTH federal and state taxes from the employee salary.
Using proper concatenation, output both the first employee's salary AND what the employee's take home pay will be after taxes are deducted.
Do the same for the second employee.
This is the code that we have:
class Employee:
fed_tax = float(.2)
state_tax = float(.0314)
def __init__(self, name, salary):
self.name = name
self.salary = salary
def apply_taxes(self):
self.salary = int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)
print("The employee, " + emp_1.name + ", salary is $" + str(emp_1.salary) + ".")
print("Employee " + emp_1.name + " will take home $" + str(emp_1.salary) + ", after taxes.")
print("The employee, " + emp_2.name + ", salary is $" + str(emp_2.salary) + ".")
print("Employee " + emp_2.name + " will take home $" + str(emp_2.salary) + ", after taxes.")
you are not calling apply taxes anywhere:
Try something like:
class Employee:
fed_tax = 0.2
state_tax = 0.0314
def __init__(self, name, salary):
self.name = name
self.salary = salary
self.post_taxed_salary = self.apply_taxes()
def apply_taxes(self):
return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
emp_1 = Employee("Isaac Soiffer", 50000)
emp_2 = Employee("Jack Fuller", 45000)
print('employee {} has salary of {} and after taxes {}'.format(emp_1.name, emp_1.salary, emp_1.post_taxed_salary))
Returns: employee Isaac Soiffer has salary of 50000 and after taxes 38430
On a note, because saalary is an attribute, you can make post_taxed_salary a property, e.g.
class Employee:
fed_tax = 0.2
state_tax = 0.0314
def __init__(self, name, salary):
self.name = name
self.salary = salary
#property
def post_taxed_salary(self):
return int(float(self.salary - ((self.salary * float(self.fed_tax)) + (self.salary * float(self.state_tax)))))
Should work as well

need help figuring out why method updating_sitting and custmor_increment are not adding and printing out the way they should

class Restaurant():
"""intalizing attributes rest._type and food_type"""
def __init__(self,resturant_type,*food_type):
self.rest_type = resturant_type
self.food = food_type
self.number_severd = 0
def opening(self):
"""Letting people know that the resturant is open"""
print(self.rest_type.title() + " is now open")
def describing_rest(self):
"""telling you about resturant"""
print("\nWelcome to " + self.rest_type.title() +
" here are what we have on the menu today: ")
for self.foods in self.food:
print("-" + self.foods)
def updating_sitting(self,new_chart):
"""updating sitting chart"""
self.number_served = new_chart
def custmor_increment(self,addition):
"""add number to custmor count"""
self.number_severd += addition
rest = Restaurant('High Spot','Turkey sandwich','pizza','deserts')
rest.opening()
rest.describing_rest()
rest.number_severd = 230
print("we have " + str(rest.updating_sitting(400)))
print("now we have " + str(rest.custmor_increment(100)))
i need help figuring out how to method updating_sitting to print out how many are sitting now
and for custmor_increment to print what the new amount of custmors there is.
To print how many are sitting, the methods need to return self.number_served.
You also need to fix the typos number_severd and your indentation.
class Restaurant():
def __init__(self,resturant_type,*food_type):
"""intalizing attributes rest._type and food_type"""
self.rest_type = resturant_type
self.food = food_type
self.number_served = 0
def opening(self):
"""Letting people know that the resturant is open"""
print(self.rest_type.title() + " is now open")
def describing_rest(self):
"""telling you about resturant"""
print("\nWelcome to " + self.rest_type.title() +
" here are what we have on the menu today: ")
for self.foods in self.food:
print("-" + self.foods)
def updating_sitting(self,new_chart):
"""updating sitting chart"""
self.number_served = new_chart
return self.number_served
def custmor_increment(self,addition):
"""add number to custmor count"""
self.number_served += addition
return self.number_served
rest = Restaurant('High Spot','Turkey sandwich','pizza','deserts')
rest.opening()
rest.describing_rest()
rest.number_served = 230
print("we have " + str(rest.updating_sitting(400)))
print("now we have " + str(rest.custmor_increment(100)))
BTW, the correct spelling of "custmor" is "customer"

class method TypeError "Int object not callable"

TypeError: 'int' object is not callable
class Car():
def __init__(self, make, model, year):
"""initialize attribuites to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
self.increment_odometer = 0
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cannot roll back the odometer.")
def read_odometer(self):
"""print at statement which shows the car's miles"""
print("This car has " + str(self.odometer_reading) + " " + "miles on it.")
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_old_car = Car ('subaru', 'outback', 2013)
print (my_old_car.get_descriptive_name())
my_old_car.update_odometer(23500)
my_old_car.read_odometer()
my_old_car.increment_odometer(100)
my_old_car.read_odometer()
Output:
2013 Subaru Outback
This car has 23500 miles on it.
Traceback (most recent call last):
File "cars.py", line 42, in <module>
my_old_car.increment_odometer(100)
TypeError: 'int' object is not callable
As mentioned you define a name for an increment_odometer object in the __init__ and later define a method with the same name. Just remove the self.increment_odometer = 0 in the __init__
class Car():
def __init__(self, make, model, year):
"""initialize attribuites to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
# self.increment_odometer = 0 ----> remove this line
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cannot roll back the odometer.")
def read_odometer(self):
"""print at statement which shows the car's miles"""
print("This car has " + str(self.odometer_reading) + " " + "miles on it.")
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_old_car = Car ('subaru', 'outback', 2013)
print (my_old_car.get_descriptive_name())
my_old_car.update_odometer(23500)
my_old_car.read_odometer()
my_old_car.increment_odometer(100)
my_old_car.read_odometer()

python. Unable to run program

I'm new to Python programming.
I was trying to achieve the following output:
Account c
Account count = 1
Successful transaction! Balance = 10000
Successful transaction! Balance = 9000
Not enough balance
My code:
class Account:
accountCount = 0
def __init__(self, name, accountNo):
self.name = name
self.accountNo = accountNo
self.balance = 0
Account.accountCount += 1
print ("Account " + self.accountNo)
print ("Account count= " +str(Account.accountCount))
def withdraw (self, amount):
self.balance -= amount
return self.balance
def deposit (self,amount):
self.balance += amount
return self.balance
myAccount = Account ("c", "c123")
myAccount.deposit(10000)
myAccount.withdraw(500)
myAccount.withdraw(10000)
I get the following error
line 1, in <module>
line 20, in Account myAccount = Account ("c", "c123")
NameError: name 'Account' is not defined
Your problem is with indentation. Moving your code logic to the beginning of the line will execute your code.
class Account:
accountCount = 0
def __init__(self, name, accountNo):
self.name = name
self.accountNo = accountNo
self.balance = 0
Account.accountCount += 1
print("Account " + self.accountNo)
print("Account count = " + str(Account.accountCount))
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
account_c = Account("c", "c123")
account_c.deposit(10000)
account_c.withdraw(500)
account_c.withdraw(10000)
Output:
Account c123
Account count = 1

Creating instances in a loop

I just started to learn about classes last week in my game dev. class. I am trying to create something that will allow me to create instances of something while in a for loop. For example, I am trying to create 5 instances of Player in a loop and use an ID number that will increase with each time the loop loops. I've gotten this far.
class Player(object):
def __init__(self, nm, am, wp, ht, ide):
self.name = nm
self.ammo = am
self.weapon = wp
self.health = ht
self.id = ide
def __str__(self):
values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
return values
def main():
Players = 0
while Players < 5:
play1 = Player("Joe", 5, "Machine gun", 22, 1)
print (play1)
Players = Players + 1
I've managed to create 5 instances of Joe which is fine, but how would I increase the ID #?
class Player(object):
def __init__(self, nm, am, wp, ht, ide):
self.name = nm
self.ammo = am
self.weapon = wp
self.health = ht
self.id = ide
def __str__(self):
values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
return values
def main():
Players = 0
while Players < 5:
play1 = Player("Joe", 5, "Machine gun", 22, Players)
print (play1)
Players = Players + 1
Use The Var Players And Put It Into The Class
I would put your players in an array so they can be used outside of the scope of the loop.
def main():
Players = 0
list_of_players = []
for i in range(5):
list_of_players.append(Player("Joe", 5, "Machine gun", 22, i+1))
print list_of_players[i]
You can use a list:
players = []
while len(players) < 5:
players.append(Player("Joe", 5, "Machine gun", 22, len(players) + 1))

Categories

Resources