【问题标题】:How to pass a variable from a function to a class python如何将变量从函数传递到类python
【发布时间】:2010-05-04 14:38:40
【问题描述】:

我正在尝试将变量从函数传递给类。示例代码如下:

def hello(var):

    return var

class test():
    def __init__(self):
        pass

    def value(self):
        print var

hello(var)
test = test()
test.value()

我想将var 传递给test() 类。

感谢您的帮助。

【问题讨论】:

标签: python class


【解决方案1】:

你需要像这样修改你的类:

class test():
    def __init__(self, var):
        self.var = var

    def value(self):
        print self.var

test_inst = test(var)
test_inst.value()

此外,您不能使用完全相同的名称来同时引用类实例和类本身。

【讨论】:

  • @SilentGhost -- 我使用了这段代码,但我得到了错误 -- Traceback (last recent call last): File "function_pass.py", line 41, in test_inst = test() TypeError: __init__() 正好接受 2 个参数(1 个给定)
  • @chriss:我不建议使用test(),我建议使用test(var)
  • 这表示当我这样做时全局var 没有定义。
  • @chriss:好吧,为什么没有定义?你的代码是从哪里来的?
  • 我可以定义它。它有效。当我通过命令行传递它时,问题就开始了。那就不接受了。感谢您的帮助。
【解决方案2】:
class test():
    def __init__(self, var):
        self._var = var

    def value(self):
        print self._var

【讨论】:

    【解决方案3】:

    添加语句:

    global var
    

    到您的代码:

    >>> global var
    >>> def hello():
           print var
    
    >>> class test():
           def __init__(self):
               pass
    
           def value(self):
               print var
    
    >>> var = 15
    >>> hello()
    15
    >>> test().value()
    15
    

    关于全局变量的标准免责声明很糟糕......但这就是你的做法。

    【讨论】:

    • 完全没有必要。
    • 是的,完全没有必要,但考虑到他的代码,这就是我认为他要问的。
    【解决方案4】:

    我认为你可以在类的函数中调用 hello 函数。

    def hello (var):
        return var
    
    class test():
        def __init__(self):
            pass
    
        def value(self):
            var = hello(5)
            print var
    
    test = test()
    test.value()
    

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      相关资源
      最近更新 更多