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

时间:2012-03-01 16:31:15

标签: python

我有一个班级和两个方法。一种方法从用户获得输入并将其存储在两个变量x和y中。我想要另一个接受输入的方法,所以将输入添加到x和y。当我为某个数字z运行calculate(z)时,它给出了错误,指出全局变量x和y未定义。显然这意味着calculate方法无法从getinput()访问x和y。我做错了什么?

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

5 个答案:

答案 0 :(得分:13)

这些必须是实例变量:

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

答案 1 :(得分: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

答案 2 :(得分:3)

xy是局部变量。当你离开那个功能的范围时,它们会被摧毁。

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

答案 3 :(得分:2)

在课程内部,您可以使用名为self的变量:

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

答案 4 :(得分:0)

dist

init方法初始化类。 辅助函数只保存一些变量/数据/属性,并在调用它时将它们释放到其他方法。这里jsonInputFile是一些json。 checkHostname是一个写入某个设备/服务器并检查主机名的方法,但它需要ip,用户名和密码,并通过调用helper方法提供。