Python 3 : Sharing variables between methods in a class

泄露秘密 提交于 2019-12-10 10:46:00

问题


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

回答1:


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)

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)



回答2:


Is this what you're 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)
        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()


来源:https://stackoverflow.com/questions/7670415/python-3-sharing-variables-between-methods-in-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!