Krzysztof Podsiadło
Krzysztof Podsiadło

Reputation: 317

Accessing an instance's methond from a function in another module

Noob question.

I have the following simple code:

class Test():

    def __init__(self):
        self.foo = "foo"

    def bar(self):
        self.foo = "bar"

def action():
    a = input("Anything>")
    spam.bar()
    print(spam.foo)

spam = Test()

action()

It displays, as expected, "bar".

When I split it into two files: test_main.py:

from test_module import action

class Test():

    def __init__(self):
        self.foo = "foo"

    def bar(self):
        self.foo = "bar"


spam = Test()

action()

And test_module.py:

def action():
    a = input("Anything>")
    spam.bar()
    print(spam.foo)

Function action() cant' access object "spam":

  File "test_main.py", line 14, in <module>
    action()
  File "/home/krzysztof/Documents/dev/Python Crash Course/12/test_module.py", line 3, in action
    spam.bar()
NameError: name 'spam is not defined'

I know that this kind of access is possible, but I can't find information on how to do it. What am I missing?

Upvotes: 0

Views: 35

Answers (4)

Arpit Gupta
Arpit Gupta

Reputation: 23

when you are importing the test module file, the entire code from that file is run before importing. So the spam variable does not exist in the test_module file. you should rather use spam as an argument in the action function.

Upvotes: 0

Solie
Solie

Reputation: 1

You can use

from test_main import bar

and you can use something like this format

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

Upvotes: -1

Bj&#246;rn
Bj&#246;rn

Reputation: 1832

You could pass spam the instance of your class to your action function as a parameter. And change the definition of your function.

test_main.py

from test_module import action 
class Test(): 
    def __init__(self): 
        self.foo = "foo" 
    def bar(self): 
        self.foo = "bar" 

spam = Test() 
action(spam)

test_module.py

def action(spam): 
    a = input("Anything>") 
    spam.bar() 
    print(spam.foo)

Upvotes: 1

Tushar Sadhwani
Tushar Sadhwani

Reputation: 565

You were previously able to access spam because it was a global variable in the same file. You cannot access globals from a different file directly.

The correct way to do this would be to change action() to take spam as a parameter:

def action(spam):
    a = input("Anything>")
    spam.bar()
    print(spam.foo)

and then call it by using action(spam) instead.

Upvotes: 1

Related Questions