5

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

import <file>

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

from <file> import <def>

but then it says global name 'x' is not defined.

So how can I do this?

Edit:

Here is a example of what I am 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 is just giving me a error though.

6
  • what are you trying to import, is it built in? and if not is it in the same directory as your working directory? Commented Jul 31, 2013 at 18:02
  • You don't import a file; you import a module, or names contained in a module. import modulename, not import filename.py. You'll need to add a more concrete example to illustrate your problem better. Commented Jul 31, 2013 at 18:05
  • Can you put the actual import statement and the actual absolute file paths in your post? Commented Jul 31, 2013 at 18:14
  • ...huh. I never thought of importing a class's methods from another module. It actually works, once you fix the syntax. I'm not sure whether it'd ever be a good idea, though. Commented Jul 31, 2013 at 18:21
  • huh... Well what is wrong with the syntax? Commented Jul 31, 2013 at 18:24

1 Answer 1

7
import file2

loads the module file2 and binds it to the name file2 in the current namespace. b from file2 is available as file2.b, not b, so it isn't recognized as a method. You could fix it with

from file2 import b

which would load the module and assign the b function from that module to the name b. I wouldn't recommend it, though. Import file2 at top level and define a method that delegates to file2.b, or define a mixin superclass you can inherit from if you frequently 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're trying to use is implemented in C.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.