简体   繁体   中英

Python Import class error, trying to understand the root directory __init__.py

I am just 4 days old to python. I am just trying to understand the root __init__.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.

I am getting error as "ImportError: cannot import name Person"

Below is the structure

Example(directory)
    model
        __init__.py (empty)
        myclass.py
    __init__.py
    run.py

myclass.py

class Person(object):
    def __init__(self):
        self.name = "Raja"

    def print_name(self):
        print self.name

__init__.py

from model.myclass import Person

run.py

from model import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()

The error basically says the interpreter can't find anything that would match Person in a given namespace, in your case model package. It's because it's in model.myclass package, but it's imported to root and not to run .

Modules in python are basically directories with __init__.py script. But it's tricky to import anything at root level from init . And moreover, it's not necessary.

OK, so this means solution is either to import directly from model package, or from the rott-level __init__.py . I would recommend the former method, since it's more commonly used. You can do it this way:

from model.myclass import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()

And leave __init__.py empty. They are used only for initialization, so there is no need to import everything to them.

You could put something to your model/__init__.py and then import it in myclass.py like:

__init__.py :

something = 0

myclass.py :

from . import something
print something

Either, as @gonczor suggested, you can simply leave __init__ empty (moreover, you don't need the root one) and import directly from the package:

from model.myclass import Person

Or, if you intentionally want to flatten the interface of the package, this is as simple as this:

model/__init__.py

from myclass import Person

run.py

from model import Person

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM