在Python中如何在方法之间传递变量?

5

我有一个类和两个方法。其中一个方法从用户那里获取输入并将其存储在两个变量 xy 中。我想要另一个方法,它接受一个输入,然后将该输入添加到 xy 中。就像这样:

class simpleclass(object):
    def getinput(self):
        x = input("input value for x: ")
        y = input("input value for y: ")
    def calculate(self, z):
        print(x + y + z)

当我运行calculate(z)来计算某个数字z时,会出现错误提示说全局变量xy未定义。
如何让calculate获取在getinput中赋值的xy值?

1
这个回答解决了你的问题吗?如何在类的方法之间共享变量? - outis
@outis,这个问题很接近,但我决定使用这个更好的版本作为规范。 - Karl Knechtel
5个回答

17

这些需要成为实例变量:

class simpleclass(object):
    def __init__(self):
        self.x = None
        self.y = None

    def getinput(self):
        self.x = input("input value for x: ")
        self.y = input("input value for y: ")
   
    def calculate(self, z):
        print(self.x + self.y + z)

2
+1 对于最正确的答案,演示 init() 方法的使用。注意:这是翻译任务,不涉及编写 Python 代码。 - Li-aung Yip

5
您想要使用self.xself.y。如下所示:
class simpleclass(object):
    def getinput(self):
        self.x = input("input value for x: ")
        self.y = input("input value for y: ")
    def calculate(self, z):
        print(self.x + self.y + z)

3

xy是局部变量。当你移出该函数的作用域时,它们将被销毁。

class simpleclass(object):
    def getinput(self):
        self.x = input("input value for x: ")
        self.y = input("input value for y: ")
    def calculate(self, z):
        print(int(self.x) + int(self.y) + z)

如果你要切换到使用raw_input,那么可能需要从字符串中获取一个数字。 - DSM

2

在类中,有一个名为 self 的变量可供使用:

class Example(object):
    def getinput(self):
        self.x = input("input value for x: ")
    def calculate(self, z):
        print(self.x + z)

0
class myClass(object):
    def __init__(self):
        pass
    
    def helper(self, jsonInputFile):
        values = jsonInputFile['values']
        ip = values['ip']
        username = values['user']
        password = values['password']
        return values, ip, username, password
    
    def checkHostname(self, jsonInputFile):
       values, ip, username, password = self.helper(jsonInputFile)
       print(values)
       print('---------')
       print(ip)
       print(username)
       print(password)

__init__方法初始化类。 helper函数仅保存一些变量/数据/属性,并在调用时将它们释放给其他方法。这里的jsonInputFile是一些JSON。 checkHostname方法登录到某个设备/服务器以检查主机名;但它需要IP、用户名和密码,这些信息通过调用helper方法获取。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接