How to pass a variable from a function to a class python

断了今生、忘了曾经 提交于 2021-02-11 17:49:38

问题


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().

Thanks for any help.


回答1:


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.




回答2:


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

    def value(self):
        print self._var



回答3:


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.




回答4:


I think you can call hello function in class's function.

def hello (var):
    return var

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

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

test = test()
test.value()


来源:https://stackoverflow.com/questions/2766239/how-to-pass-a-variable-from-a-function-to-a-class-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!