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
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.
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With