【问题标题】:Passing variables between methods in Python?在 Python 中的方法之间传递变量?
【发布时间】:2012-03-20 04:13:10
【问题描述】:

我有一个类和两个方法。一种方法从用户那里获取输入并将其存储在两个变量 x 和 y 中。我想要另一种接受输入的方法,以便将该输入添加到 x 和 y。当我为某个数字 z 运行 calculate(z) 时,它给了我错误,说全局变量 x 和 y 没有定义。显然,这意味着计算方法无法从 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

【问题讨论】:

标签: python


【解决方案1】:

这些必须是实例变量:

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 表示使用 __init__() 方法的最正确答案。
【解决方案2】:

您想使用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

【讨论】:

  • @DSM:天哪!接得好。编辑修复。
【解决方案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

【讨论】:

  • 如果你切换到 raw_input,可能想在某个时候从字符串中获取一个数字。
【解决方案4】:

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

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

【讨论】:

    【解决方案5】:
    class myClass(object):
    
        def __init__(self):
    
        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
           print values
           print '---------'
           print ip
           print username
           print password
    

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

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 2013-10-30
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      相关资源
      最近更新 更多