파이썬/모듈
모듈과 클래스
코린이도이
2021. 3. 30. 14:50
- 클래스: 어떤 프로그래밍 객체를 생성하기 위한 설계도, 모듈 안에는 변수, 함수, 클래스가 있을 수 있다.
shapes2d.py
#원 클래스
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
#정사각형 클래스
class Square:
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
다른 파일에서 이 클래스들을 사용하려면 전 게시글과 같이 import 키워드를 사용하면 됨
run.py
#import <module>
import shapes2d
circle = shapes2d.Circle(2)
print(circle.area())
#from <module> import <member(s)>
from shapes2d import Square
square = Square(3)
print(square.area())
물론 as 키워드를 사용해서 임포트하는 것의 이름을 바꿔줄 수도 있다.
run.py
from shapes2d import Square as Sq
square = Sq(3)
print(square.area())