본문 바로가기
파이썬

모듈만들고 불러오기_2 (sys.path.append(모듈절대경로))

by 혜룐 2015. 11. 10.
https://wikidocs.net/29
mod4라는 모듈을 만든다.
cat mod4.py
PI = 3.14
class Math:
def solv(self, r):
return PI * (r ** 2)
def sum(self,a,b):
return a+b
if __name__ == "__main__":
print PI
a = Math()
print a.solv(4)
testMod4.py 파일에 mod4를 import 한다.
import mod4
모듈안에 있는 클래스를 쓰기 위해서는, . 를 이용해,
클래스이름 앞에 모듈 이름을 먼저
써주어야 한다.
a = mod4.Math()
단, 사용하려는 모듈이 같은 디렉터리에 위치해야 한다.
바로, 불러서 쓰려면? : sys.path.append("/m/script/python/module")
[root@tpl-master module]# cat testMod4.py 
#!/usr/bin/python
## import
def testImport():
#from mod4 import *
import mod4
a = mod4.Math()
print a.solv(5)
testImport()
위에 예는, 파일과 모듈이 한 디렉터리에 위치해야 한다.
sys.path.append(모듈절대경로) 를 통해, 바로 사용할수 있다.
전에 만들었던, calc 모듈에 있는 사칙연산을 하는 클래스(Calc)를 호출해 사용해보자.
calcChild 라는 클래스는 Calc라는 부모클래스를 상속받는다. 그리고 minus 라는 멤버함수는 x-y 가 아니라, y-x 연산이 이뤄지도록 오버라이딩한다.
(1) cacl 모듈이다.
[root@tpl-master file]# cat ../calc.py
#!/usr/bin/python
class Calc:
def __init__(self, x, y):
self.x = x
self.y = y
def sum(self):
return int(self.x) + int(self.y)
def minus(self):
return int(self.x) - int(self.y)
def mul(self):
return int(self.x) * int(self.y)
def div(self):
return float(self.x) / float(self.y)
def nam(self):
return float(self.x) % float(self.y)
if __name__ == "__main__":
sample = Calc(10, 2)
print 'sample.x :', sample.x , '\t' , 'sample.y :', sample.y
print 'SUM : ',sample.sum() , '\t', 'MINUS : ', sample.minus(), '\t', 'MUL : ', sample.mul(), '\t', 'DIV' , sample.div(), '\t', 'NAM :' , sample.nam()
print type(sample)
print type(Calc)
(2) calc 모듈 위치와 다른, useModule.py
[root@tpl-master file]# cat useModule.py 
#!/usr/bin/python
import sys
print sys.path
sys.path.append("/daum/script/python/module")
sys.path.append("/daum/script/python")
print sys.path
import mod4
import calc
a =
mod4.Math()
print a.solv(10)
class CalcChild(
calc.Calc
):
def minus(self):
return int(self.y) - int(self.x)
sample = CalcChild(10, 2)
print sample.sum()
print sample.minus()