简体   繁体   English

如何将变量从函数传递给类python

[英]How to pass a variable from a function to a class python

I am trying to pass a variable from a function to a class. 我试图将变量从函数传递给类。 Example code is below: 示例代码如下:

def hello(var):

    return var

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

    def value(self):
        print var

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

I would like to pass var into the class test() . 我想将var传递给类test()

Thanks for any help. 谢谢你的帮助。

You need to modify your class like this: 您需要像这样修改您的课程:

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

    def value(self):
        print self.var

test_inst = test(var)
test_inst.value()

Also, you cannot use the same exact name to refer to both class instance and a class itself. 同样,您不能使用相同的确切名称来引用类实例和类本身。

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

    def value(self):
        print self._var

Add the statement: 添加语句:

global var

to your code: 您的代码:

>>> global var
>>> def hello():
       print var

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

       def value(self):
           print var

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

Cue standard disclaimer regarding global variables are bad... but this is how you do it. 提示有关全局变量的标准免责声明是不好的……但这就是您的做法。

I think you can call hello function in class's function. 我认为您可以在类的函数中调用hello函数。

def hello (var):
    return var

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

    def value(self):
        var = hello(5)
        print var

test = test()
test.value()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM