Python: import another .py file

I have a class and I want to import the def function by doing:

import <file> 

but when I try to call it, it says that def cannot be found. I also tried:

 from <file> import <def> 

but then he says that the global name "x" is undefined.

So how can I do this?

Edit:

Here is an example of what I'm trying to do. In file1.py I have:

 var = "hi" class a: def __init__(self): self.b() import file2 a() 

and in file2.py I have:

 def b(self): print(var) 

it just gives me an error.

+6
source share
1 answer
 import file2 

loads the file2 module and associates it with the file2 name in the current namespace. b from file2 is available as file2.b , not b , so it is not recognized as a method. You can fix it with

 from file2 import b 

which will load the module and assign function b from this module to the name b . I would not recommend it. Import file2 at the top level and define a method that delegates file2.b , or define a superclass that you can inherit if you often need to use the same methods in unrelated classes. Importing a function to use it as a method is confusing, and it breaks if the function you are trying to use is implemented in C.

+7
source

Source: https://habr.com/ru/post/950746/