James Clarke
James Clarke

Reputation: 29

Python how to share an object between methods in a class?

I am making a game that requires an object to be shared between multiple methods in a class, I am having issues where the methods don't recognise the object even though it has been created. Here is an example of what I am talking about:

import Economy

Class Example:
    economy = Economy.Economy()

    def __init__(self, test):
        self.test = test
    def exampleMethod1(self):
        economy.getMoney()
    def exampleMethod2(self)
        economy.addMoney(1)

Python gives me an error in the methods and says the object doesn't exist.

Upvotes: 0

Views: 79

Answers (1)

BluCode
BluCode

Reputation: 1097

You can use the self object to share objects between methods of a class. Your code would become:

import Economy

Class Example:
    economy = Economy.Economy()

    def __init__(self, test):
        self.test = test
    def exampleMethod1(self):
        self.economy.getMoney()
    def exampleMethod2(self)
        self.economy.addMoney(1)

Hope this helps you.

Upvotes: 2

Related Questions