【问题标题】:How to share variables between methods in a class? [duplicate]如何在类中的方法之间共享变量? [复制]
【发布时间】:2011-12-01 23:52:04
【问题描述】:

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

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

#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

【问题讨论】:

  • 同一个类,还是同一个对象?
  • 看不懂tutorial的人很抱歉...
  • @mkrieger1:另一个不应该被标记为这个的副本吗?这个问题早于另一个问题,既没有公认的答案,也没有最高级的质量,也没有另一个问题的答案中缺少信息的答案。
  • @outis 我发现另一个问题更清楚了。

标签: python oop methods


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    这是你想要做的吗?

    #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()
    

    【讨论】:

      猜你喜欢
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多