开发者

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

This question already has answers here: Using global variables in a function (25 answers) How do I get a result (output) from a function? How can I use the result later? (4 answers) Closed 5 months ago.

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.开发者_高级运维


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.

def hello (var):
    return var

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

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

test = test()
test.value()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜