Nice programing

동일한 디렉토리 또는 하위 디렉토리 내에서 클래스를 가져 오는 방법은 무엇입니까?

nicepro 2020. 10. 3. 11:51
반응형

동일한 디렉토리 또는 하위 디렉토리 내에서 클래스를 가져 오는 방법은 무엇입니까?


모든 .py 파일 을 저장하는 디렉토리가 있습니다.

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

나는에서 클래스를 사용하려는 user.pydir.pymain.py .
이 Python 클래스를 main.py 로 어떻게 가져올 수 있습니까?
또한 user.py 가 하위 디렉토리에 User있으면 어떻게 클래스를 가져올 수 있습니까?

bin/
    dir.py
    main.py
    usr/
        user.py

파이썬 2

파일 __init__.py과 같은 디렉토리에 빈 파일을 만듭니다 . 이것은 파이썬에게 "이 디렉토리에서 가져 오기 가능"을 의미합니다.

그럼 그냥 ...

from user import User
from dir import Dir

파일이 하위 디렉터리에있는 경우에도 마찬가지 __init__.py입니다. 하위 디렉터리에도를 넣은 다음 점 표기법과 함께 일반 import 문을 사용합니다. 디렉토리의 각 레벨에 대해 가져 오기 경로에 추가해야합니다.

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

따라서 디렉토리 이름이 "classes"이면 다음과 같이합니다.

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

파이썬 3

이전과 동일하지만 .하위 디렉토리를 사용하지 않는 경우 모듈 이름에 접두사를 붙입니다 .

from .user import User
from .dir import Dir

방금 배웠습니다 ( martineau의 의견 덕분에 ) 동일한 디렉토리 내의 파일에서 클래스를 가져 오려면 이제 Python 3으로 작성해야합니다.

from .user import User
from .dir import Dir

귀하의 main.py:

from user import Class

여기서 Class가져올 클래스의 이름입니다.

의 메서드를 Class호출하려면 다음을 사용하여 호출 할 수 있습니다.

Class.method

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


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)

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]:

from user import User 
from dir import Dir 

Python 3


Same directory.

import file:log.py

import class: SampleApp().

import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

or

directory is basic.

import in file: log.py.

import class: SampleApp().

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

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.


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

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

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

참고URL : https://stackoverflow.com/questions/4142151/how-to-import-the-class-within-the-same-directory-or-sub-directory

반응형