Python(모듈)

짬그브·2025년 4월 9일

모듈

모듈에 클래스 작성하기

import 모듈
모듈.클래스()

from import 로 클래스 가져오기

모듈에서 from import로 클래스를 가져온 뒤 모듈 이름을 붙이지 않고 사용할 수도 있음

square 코드

base = 2

def square(n):
    return base ** n

main코드

from modulePart import square1 as sq

print(sq.base)
print(sq.square(10))

from modulePart.square1 import base, square

print(base)
print(square(10))

결과값

2
1024
2
1024

Person 코드

class Person:
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

    def greeting(self):
        print('안녕하세요 저는 {} 입니다. 나이는 {} 입니다.'.format(self.name,self.age))

main2코드

from modulePart import person

obj = person.Person('kim',  30, 'seoul')
obj.greeting()
print()

from modulePart.person import Person as ps

obj2 = ps('Lee',  22, 'busan')
obj2.greeting()

결과값

안녕하세요 저는 kim 입니다. 나이는 30 입니다.

안녕하세요 저는 Lee 입니다. 나이는 22 입니다.

모듈과 시작점 알아보기

파이썬 코드를 보다 보면 ifname=='main': 으로 시작하는 부분을 자주 만나게 됨

이 코드는 현재 스크립트 파일이 실행되는 상태를 파악하기 위해 사용함

name__ 변수를 통해 현재 스크립트 파일이 시작점인지 모듈인지 판단함

ifname=='main':처럼 name 변수의 값이 'main'인지 확인하는 코드는 현재 스크립트 파일이 프로그램의 시작점이 맞는지 판단하는 작업임

스크립트 파일이 메인 프로그램으로 사용될 때와 모듈로 사용될 때를 구분하기 위한 용도임

hello 파일

print('hello 모듈 시작')
print('hello.py __name__:',__name__)
print('hello 모듈 종료')

if __name__ == '__main__':
    print()
    print('main으로 실행 할 때만 출력')

main3 파일

from modulePart import hello

결과값

hello 파일 실행

hello 모듈 시작
hello.py __name__: __main__
hello 모듈 종료

main으로 실행 할 때만 출력

main3 파일 실행

hello 모듈 시작
hello.py __name__: modulePart.hello
hello 모듈 종료

스크립트 파일로 실행하거나 모듈로 사용하는 코드 만들기

main4 파일

from modulePart import calc

if __name__ == '__main__':
    print(calc.add(10,20))
    print(calc.mul(10,20))

calc파일

def add(a,b):
    return a + b

def mul(a,b):
    return a * b

if __name__ == '__main__':
    print(add(100,200))
    print(mul(100,200))

결과값

main4 파일실행

30
200

calc 파일실행

300
20000

모듈로 가져왔을 때는 아무것도 출력되지 않은것은 name 변수의 값이 'main'일 때만 10, 20의 합과 곱을 출력하도록 만들었기 때문

패키지에 모듈 만들기

첫 번째 모듈은 덧셈, 곱셈 함수가 들어있는 operator 모듈이고 , 두 번째 모듈은 삼각형, 사각형의 넓이 계산 함수가 들어잇는 geometry 모듈임

패키지 사용하기

내용들을 프로젝트 폴더 안에 main6.py 파일로 저장한 뒤 실행

init 파일

from. import operator
from. import geometry

operator 파일

def add(n1, n2):
    return n1 + n2

def mul(n1, n2):
    return n1 * n2

geometry 파일

def triangle_area(base, height):
    return base * height / 2

def rectangle_area(width, height):
    return width * height

main6 파일

import modulePart

print(modulePart.operator.add(10,20))
print(modulePart.geometry.rectangle_area(20,20))

from modulePart import *
print(operator.mul(10,20))
print(geometry.triangle_area(10,20))

from modulePart.operator import *
from modulePart.geometry import *

print(mul(100,200))
print(rectangle_area(100,200))

main 6 파일 실행시

결과값

30
400
200
100.0
20000
20000
profile
+AI to AI+

0개의 댓글