본문 바로가기
Programming/Python

파이썬 코딩 따라하기(기본) - 패키지

by Deongeun 2021. 1. 14.

 

 

패키지(Package)

: '.'을 이용하여 파이썬 모듈을 계층(디렉터리) 구조로 관리할 수 있게 해준다.

 

<패키지 구조>

Home/

   __init__.py

   Livingroom.py

   Kitchen.py

   test.py

- Home 이라는 파일을 만들어주고 그 아래에 

  __init__, Livingroom, Kitchen, test 라는 .py 파일을 생성해주었다

- Home은 디렉터리 이름이고, .py확장자를 가진 파일은 모듈이 된다.

 

# Livingroom.py

class LivingroomPackage:
	def detail(self):
    	print("This is the Livingroom")
# Kitchen.py

class KitchenPackage:
	def detail(self):
    	print("This is the Kitchen")

- 위와 같은 코드를 각각 .py 파일에 입력해준다

 

 

불러오기
import Home.Livingroom
space = Home.Livingroom.LivingroomPackage()
space.detail()

- import를 이용해 위와 같이 불러올 수 있는데,

  변수 'space'를 지정하여 패키지 . 모듈 . 클래스를 적용하고, 함수 'detail' 까지 불러올 수 있다.

 

- 단, 이때 클래스나 함수는 import문에서 직접 불러올 수 없다.

  import 패키지 . 모듈 (o)

  import 패키지 . 모듈 . 클래스 (x)

 

 

from Home.Livingroom import LivingroomPackage
space = LivingroomPackage()
space.detail()
from Home import Kitchen #모듈까지만 import
space = Kitchen.KitchenPackage()
space.detail()

- from import문에서는 클래스, 함수를 직접 불러올 수 있다.

  from 패키지 . 모듈 import 클래

 

 

 

 

 

__init__.py 

: 이 파일은 해당 디렉터리를 패키지로 인식시켜주는 역할을 한다.

 

 

 

 

 

__all__

from ______ import *의 방식으로

from Home import *
space = LivingroomPackage()
space.detail()

를 써주고 위와 똑같이 불러오려고 하면 Livingroom을 찾을 수 없다는 Traceback error가 뜨게된다.

* 기호를 이용하여 import 할 때는 import 범위 설정을 해줘야하는데, 

  무엇을 불러오고 무엇을 불러오지 않을지 설정하는 것이다.

 

- __init__.py 파일에

__all__ = ["Livingroom"]

위와 같이 적어주면 에러가 뜨지않고 원하는 결과를 다시 얻을 수 있다.

 

 

 

 

 

inspect

* 패키지나 모듈 파일은 모듈, 패키지를 호출하는 test.py같은 파일과 동일한 위치에 있거나 파이썬 내에 라이브러리들이 모여있는 폴더에 있어야 사용가능하다.

이때 파일 위치를 알아낼 수 있는것이 inpsect인데,

from Home import *
import inspect
print(inspect.getfile(Livingroom.py))

위와 같이 입력하면 파일경로를 알아낼 수 있다.

 

 

from random import *
print(inspect.getfile(random))

# 결과값 -> C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\random.py

위의 Python38-32\lib이 기본적인 파이썬 내 라이브러리들이 모여있는 폴더다