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

后端 未结 13 898
醉梦人生
醉梦人生 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:47

    If user.py and dir.py are not including classes then

    from .user import User
    from .dir import Dir
    

    is not working. You should then import as

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

    I'm not sure why this work but using Pycharm build from file_in_same_dir import class_name

    The IDE complained about it but it seems it still worked. I'm using Python 3.7

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

    Python3

    use

    from .user import User inside dir.py file
    

    and

    use from class.dir import Dir inside main.py
    or from class.usr import User inside main.py
    

    like so

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

    To make it more simple to understand:

    Step 1: lets go to one directory, where all will be included

    $ cd /var/tmp
    

    Step 2: now lets make a class1.py file which has a class name Class1 with some code

    $ cat > class1.py <<\EOF
    class Class1:
        OKBLUE = '\033[94m'
        ENDC = '\033[0m'
        OK = OKBLUE + "[Class1 OK]: " + ENDC
    EOF
    

    Step 3: now lets make a class2.py file which has a class name Class2 with some code

    $ cat > class2.py <<\EOF
    class Class2:
        OKBLUE = '\033[94m'
        ENDC = '\033[0m'
        OK = OKBLUE + "[Class2 OK]: " + ENDC
    EOF
    

    Step 4: now lets make one main.py which will be execute once to use Class1 and Class2 from 2 different files

    $ cat > main.py <<\EOF
    """this is how we are actually calling class1.py and  from that file loading Class1"""
    from class1 import Class1 
    """this is how we are actually calling class2.py and  from that file loading Class2"""
    from class2 import Class2
    
    print Class1.OK
    print Class2.OK
    EOF
    

    Step 5: Run the program

    $ python main.py
    

    The output would be

    [Class1 OK]: 
    [Class2 OK]:
    
    0 讨论(0)
  • 2020-11-22 06:50

    Just too brief, Create a file __init__.py is classes directory and then import it to your script like following (Import all case)

    from classes.myscript import *
    

    Import selected classes only

    from classes.myscript import User
    from classes.myscript import Dir
    
    0 讨论(0)
  • 2020-11-22 06:51
    from user import User 
    from dir import Dir 
    
    0 讨论(0)
提交回复
热议问题