Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share variables between methods in a class? [duplicate]

I'm looking for a way to make a variable set by one method/function in a class accessible by another method/function in that same class without having to do excess (and problematic code) outside.

Here is an example that doesn't work, but may show you what I'm trying to do :

#I just coppied this one to have an init method
class TestClass(object):

    def current(self, test):
        """Just a method to get a value"""
        print(test)
        pass

    def next_one(self):
        """Trying to get a value from the 'current' method"""
        new_val = self.current_player.test
        print(new_val)
        pass
like image 792
Charles Becker Avatar asked Oct 06 '11 04:10

Charles Becker


People also ask

How do I access a variable of one method inside another method in the same class in Python?

The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.

Can methods share variables?

Variables declared inside a method are instance variables and their scope is only within the method itself. You can not access a variable declared inside one method from another.

How do you pass values between methods in C#?

If you had more than one value to return you could use a struct/class or mark parameters as ref allowing you to modify from within the function (variables passed by reference, as opposed to passing them by value which is done by default).


1 Answers

You set it in one method and then look it up in another:

class TestClass(object):

    def current(self, test):
        """Just a method to get a value"""
        self.test = test
        print(test)

    def next_one(self):
        """Trying to get a value from the 'current' method"""
        new_val = self.test
        print(new_val)

As a note, you will want to set self.test before you try to retrieve it. Otherwise, it will cause an error. I generally do that in __init__:

class TestClass(object):

    def __init__(self):
        self.test = None

    def current(self, test):
        """Just a method to get a value"""
        self.test = test
        print(test)

    def next_one(self):
        """Trying to get a value from the 'current' method"""
        new_val = self.test
        print(new_val)
like image 130
cwallenpoole Avatar answered Oct 21 '22 19:10

cwallenpoole