luckyseafood
luckyseafood

Reputation: 17

How can I use a variable from a different method in the same class without putting it as a parameter?

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

Answers (2)

Towsif Ahamed Labib
Towsif Ahamed Labib

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

CryptoFool
CryptoFool

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

Related Questions