linus72982
linus72982

Reputation: 1393

Python -- calling a function in same file as a class from within an instance of that class?

I have a file structured like this:

imports

def myFunc(spam):
    etc

class MyClass():
    def someMethod(self):
         myFunc(eggs)

I don't think this works as I understand that functions assume scope local to just that function. How would I accomplish this? It seems silly to import itself and then call imported.myFunc()

In case there are those that need to know why -- this is a file called utilities and the class is Database that contains my database wrapper stuff. Outside of it are utility functions. I'd prefer to keep Database inside of utilities, if possible.

Upvotes: 3

Views: 15135

Answers (2)

mike d
mike d

Reputation: 58

The scope of a given identifier is determined by the location of its definition. myFunc is defined at the file level, so it is visible within someMethod since it is in the same file.

Upvotes: 2

David542
David542

Reputation: 110592

You should be able to call any function outside your Class with the normal function call (as you have it in someMethod).

If you prefer to have the function inside your Class as a method, the call would then be self.myFunct(...).

Upvotes: 0

Related Questions