Hi,

I'm a bit stuck on getting 1 function that's not inside any class or function, accessible or callable to everyother part of the program, from within classes and the Main function.. i've tried to make it global but i'm not sure on how to make it work and it looks ugly..

Has anyone ever needed to do this before? if so how can it be done, much help needed please

thanks
a1eio

I probably don't understand your question, but you should be OK as long as you actually "execute" the def statement. Just having a function definition in your file is not enough, you've got to execute it. Thus

def foo(bar):
    print "BAR", bar

foo("Hello!")

works, whereas

foo("Hello!")

def foo(bar):
    print "BAR", bar

fails.

class testClass:
    def show(self, data):
        print data

def Function(data):
    variable.show(data)

def Main():
    variable = testClass()

    Function("hello")

if __name__ == '__main__':
    Main()

I want 'Function' to be accesible in that way, thats just an example, in the program 'Function' is needed like that elsewhere.
At the moment i'm just making the 'variable' global in the Main function where variable is defined and in 'Function' where it's used so..

def Function(data):
    global variable
    variable.show(data)
...
...
def Main():
    global variable
    variable = testClass()
...

it works, but i wish there was a way without globals

Try it this way ...

# recommended Python style is to start
# class names with an upper case letter
# function names with a lower case letter

class TestClass(object):
    def show(self, data=None):
        print data


def funk(data):
    instance.show(data)

def main():
    #instance = TestClass()
    funk("hello")

# create an instance of the class
instance = TestClass()

if __name__ == '__main__':
    main()

Is there something wrong with passing the instance as a parameter to Function()? I.e., Function(variable, "Hello") .

Is this issue more about the scoping of the variable, rather than the function?

This question has already been answered. Start a new discussion instead.