Python 3:在类中的方法之间共享变量
问题描述:
寻找如何使一个类中的一个方法/函数设置的变量可被同一类中的另一个方法/函数访问,而不必在外部执行过多的操作(和有问题的代码).
Looking for how to make a variable set by one Method/function in a class accessible to 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
答
您在一种方法中进行设置,然后在另一种方法中进行查找:
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)
请注意,在尝试检索self.test
之前,需要先进行设置.否则,将导致错误.我通常在__init__
中这样做:
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)