0

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.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
chrisg
  • 40,337
  • 38
  • 86
  • 107
  • Are you trying to do something similar to: http://stackoverflow.com/questions/2040998/how-to-change-variables-in-python ? – MikeyB May 04 '10 at 15:24

4 Answers4

7

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.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • @SilentGhost -- I used this code but I got the error -- Traceback (most recent call last): File "function_pass.py", line 41, in test_inst = test() TypeError: __init__() takes exactly 2 arguments (1 given) – chrisg May 04 '10 at 14:57
  • @chriss: I didn't suggest to use `test()`, I suggested to use `test(var)` – SilentGhost May 04 '10 at 15:00
  • That says that the global `var` is not defined when I do that. – chrisg May 04 '10 at 15:08
  • @chriss: well, why is it not defined? where does come from in your code? – SilentGhost May 04 '10 at 15:12
  • I can define it. And it works. It's when I pass it in via the command line the problem starts. It won't accept it then. Thanks for the help. – chrisg May 04 '10 at 15:31
0
class test():
    def __init__(self, var):
        self._var = var

    def value(self):
        print self._var
Tuomas Pelkonen
  • 7,783
  • 2
  • 31
  • 32
0

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.

MikeyB
  • 3,288
  • 1
  • 27
  • 38
0

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()
chnet
  • 1,993
  • 9
  • 36
  • 51