Python 3:在类中的方法之间共享变量 [英] Python 3 : Sharing variables between methods in a class
本文介绍了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)
这篇关于Python 3:在类中的方法之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文