0

Suppose I have a directory with files classfile.py and a test_classfile.py

here's classfile.py

class Student:

     def __init__(self, fname, lname):
          self.firstname = fname
          self.lastname = lname

     def printname(self):
          return (self.firstname + self.lastname)


if __name__ == '__main__':
     s = Student('John', 'Doe')

What I'd like to do is import just the object s into the test_file.py

something like this,

from dir.classfile.Student import s


def test_classfile():
    assert str(s.printname()).isalpha()

I get the following error

ModuleNotFoundError: No module named 'dir.classfile.Student'; 'dir.classfile' is not a package
1
  • What do you think this line does? if __name__ == '__main__': There are other things wrong here but to me this is the most blatant one. Commented May 15, 2020 at 12:35

1 Answer 1

1

As it is said 'dir.classfile' is not a package. If your .py files are both in the same directory, you just do 'import classfile'. Suppose the classfile.py was in the different directory, you would have to do the following:

import os.path
path_to_mods = os.path.abspath('path/to/classfile')
sys.path.insert(0, path_to_mods)
import classfile

You cannot import from 'Student' - this is an object. But you can import Student like this:

from classfile import Student

Also you cannot import instance of the class which is s. You should import the object like it it said above and then create an instance of it.

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.