python - 如何在类中的方法之间共享变量?

标签 python oop methods

<分区>

我正在寻找一种方法,使一个类中的一个方法/函数设置的变量可以被同一个类中的另一个方法/函数访问,而无需在外部执行过多(和有问题的代码)。

这是一个不起作用的示例,但可以向您展示我正在尝试做的事情:

#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

最佳答案

您在一种方法中设置它,然后在另一种方法中查找它:

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__ 中这样做:

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 - 如何在类中的方法之间共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670415/

相关文章:

Python 安全字典导航,正确的方法

Python Tkinter,通过在进入新窗口(新类)时引入变量来避免代码重复

python - 在Python中的文件之间传递变量

S4 类中的 R 公共(public)方法

java - 为数组创建 "reset to original values"方法(开始 java)

java - 员工商店的编辑方法。(使用Hashmap)

python - 如何正确分配_ids?

java - 抽象类中的空具体方法是否有任何理由?

java - 为什么某些 API(如 JCE、JSSE 等)通过单例映射提供可配置属性?

java - 调用另一个文件的方法