Reputation: 17
I have a class called "save", and it is a child of class "budget". I have a variable called saving and I want to use that in multiple methods of class "save".
This is the chunk of code:
class save(budget):
def show(self):
print('you have this much money to save:')
saving = saving+(self.money * 0.4)
print(saving)
def spend(self):
saved = int(input('How much have you set aside to save from this paycheck?'))
saving = saving-saved
print('This is how much you need to save: '+str(self.money))
I would also prefer a solution without using the keyword global.
Upvotes: 1
Views: 50
Reputation: 686
class save(budget):
def __init__(self, amount):
self.saving = amount
def show(self):
print('you have this much money to save:')
self.saving += (self.money * 0.4)
print(self.saving)
def spend(self):
saved = int(input('How much have you set aside to save from this paycheck?'))
self.saving -= saved
print('This is how much you need to save: '+str(self.money))
account=save(500)
Does this work for you?
Upvotes: 0
Reputation: 23089
Here's an illustration of how to do this, as @TomKarzes correctly outlines:
class save(budget):
def __init__(self):
super().__init__()
self.saving = 0
def show(self):
print('you have this much money to save:')
self.saving = self.saving+(self.money * 0.4)
print(self.saving)
def spend(self):
saved = int(input('How much have you set aside to save from this paycheck?'))
self.saving = self.saving-saved
print('This is how much you need to save: '+str(self.money))
One thing about your code, assuming this is the logic you expected...your show()
method changes the value of the self.saving
variable each time it is called. I wouldn't expect that from a method with that name, so I wonder if maybe you mean:
def show(self):
print('you have this much money to save:')
print(self.saving+(self.money * 0.4))
Upvotes: 3