How to import the class within the same directory or sub directory?

后端 未结 13 899
醉梦人生
醉梦人生 2020-11-22 06:34

I have a directory that stores all the .py files.

bin/
   main.py
   user.py # where class User resides
   dir.py # where class Dir resides
         


        
相关标签:
13条回答
  • 2020-11-22 06:52

    I just learned (thanks to martineau's comment) that, in order to import classes from files within the same directory, you would now write in Python 3:

    from .user import User
    from .dir import Dir
    
    0 讨论(0)
  • 2020-11-22 06:53

    to import from the same directory

    from . import the_file_you_want_to_import 
    

    to import from sub directory the directory should contain

    init.py

    file other than you files then

    from directory import your_file

    0 讨论(0)
  • 2020-11-22 06:54

    In python3, __init__.py is no longer necessary. If the current directory of the console is the directory where the python script is located, everything works fine with

    import user
    

    However, this won't work if called from a different directory, which does not contain user.py.
    In that case, use

    from . import user
    

    This works even if you want to import the whole file instead of just a class from there.

    0 讨论(0)
  • 2020-11-22 07:02

    You can import the module and have access through its name if you don't want to mix functions and classes with yours

    import util # imports util.py
    
    util.clean()
    util.setup(4)
    

    or you can import the functions and classes to your code

    from util import clean, setup
    clean()
    setup(4)
    

    you can use wildchar * to import everything in that module to your code

    from util import *
    clean()
    setup(4)
    
    0 讨论(0)
  • 2020-11-22 07:07

    Python 2

    Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

    Then just do...

    from user import User
    from dir import Dir
    

    The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

    bin/
        main.py
        classes/
            user.py
            dir.py
    

    So if the directory was named "classes", then you'd do this:

    from classes.user import User
    from classes.dir import Dir
    

    Python 3

    Same as previous, but prefix the module name with a . if not using a subdirectory:

    from .user import User
    from .dir import Dir
    
    0 讨论(0)
  • 2020-11-22 07:08

    In your main.py:

    from user import Class
    

    where Class is the name of the class you want to import.

    If you want to call a method of Class, you can call it using:

    Class.method

    Note that there should be an empty __init__.py file in the same directory.

    0 讨论(0)
提交回复
热议问题