Python 3:在类中的方法之间共享变量

时间:2011-10-06 04:55:18

标签: python oop scope

寻找如何通过一个方法/函数在同一个类中的另一个方法/函数可访问的类中创建一个变量,而不必在外面做多余的(和有问题的代码)。

这是一个不起作用的例子,但可能会告诉你我正在尝试做什么:

#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

2 个答案:

答案 0 :(得分:9)

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

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)

答案 1 :(得分:0)

这是你想要做的吗?

#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)
        self.value = test
        pass

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

a = TestClass()
b = TestClass()
a.current(10)
b.current(5)
a.next_one()
b.next_one()