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

mon*_*ith 2 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
Run Code Online (Sandbox Code Playgroud)

tur*_*der 14

这些必须是实例变量:

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
Run Code Online (Sandbox Code Playgroud)

  • +1 表示最正确的答案说明了 __init__() 方法的使用。 (2认同)

Li-*_*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
Run Code Online (Sandbox Code Playgroud)