0

I am new to OOP in python and have mostly only used it for static scoped methods. My question is this: if I want to declare a class "myclass.py" for importing into another "other.py", and myclass has dependencies on other modules, where do I import those dependencies?

#myclass.py
import numpy as np

class myclass:
   def mymethod():
       return np.array([1,2,3,4])

or is this needed:

#myclass.py

class myclass:
   import numpy as np
   def mymethod():
       return np.array([1,2,3,4])

and

#other.py

import myclass

instance = myclass()
array = instance.mymethod()

So question, where do I import numpy as np? inside myclass.py or other.py or both?

Filibuster
  • 51
  • 1
  • 3
  • " I want to declare a class "myclass.py" " woah woah. You *define* classes using the class definition statement (or even directly using the `type` constructor), this has nothing to do with source-code files. `myclass.py` is not a typical pattern, Python != Java – juanpa.arrivillaga Nov 10 '21 at 01:05
  • You should probably just `import numpy` at the top of `myclass.py`. – juanpa.arrivillaga Nov 10 '21 at 01:06
  • Honestly, I'm not even sure what this question has to do with classes or OOP. I think that's a red herring tripping you up. – juanpa.arrivillaga Nov 10 '21 at 01:09

1 Answers1

0

This question has been answered here: https://stackoverflow.com/a/128577/13945514 In short, the top answer says it is a matter of efficiency, but importing at the beginning of a script or within a function both work.

E. B.
  • 1
  • 1
    Welcome back to Stack Overflow. As a reminder about [answer]: if you believe the question has already been answered at a previous Stack Overflow question, that is what we consider a *duplicate*. Instead of using the answer section, vote to close the question, or if you aren't sure, leave a comment. – Karl Knechtel Nov 10 '21 at 00:41
  • This seems to answer the question about whether to put it at the top of the module, however, it doesnt explain to me whether or not the dependencies imported within a module will be imported once again when I import that same module from outside. – Filibuster Nov 10 '21 at 02:57