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

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

提交回复
热议问题