파이썬 사용해보기 - 5

2023. 1. 27. 19:04프로그래밍

728x90

 

 

파이썬 사용해보기 - 5

그 이외에 내가 궁금한 내용에 대해서 프로그램을 만들어 보면서, 알아보기로 한다. 현재까지의 모든 소스...

blog.naver.com

 

그 이외에 내가 궁금한 내용에 대해서 프로그램을 만들어 보면서, 알아보기로 한다.

현재까지의 모든 소스는 첨부파일에 다 있다.

 

1. 정적 메서드 만들기

간단하다! 하나만 선언 해 주면 된다 -> @staticmethod

class TobeeStaticClass:
	message = ""

	def __init__(self, message): # 생성자 / 객체 생성시 호출.
		self.message = message

	@staticmethod
	def showMyMessage(self): 
		print "정적 메서드 알지? "

	def __del__(self): # 소멸자 / 객체 소멸시 호출
		message = None
 

그리고 다음과 같이 호출 해 주면 끝!

lib_tobee.TobeeStaticClass.showMyMessage()
 

2. 여러값 리턴하기 

여러가지 값을 리턴 하고 싶을 때는?

위의 클래스에서 하나 더 만들어 보자.

@staticmethod
def returnMultiVals():
    return [1,2,3]
 

그럼 이렇게 선언한 메서드에서 다시 값을 받을 때는?

a,b,c = lib_tobee.TobeeStaticClass.returnMultiVals()
print '리턴 값이예요 [%d,%d,%d]' % (a,b,c)
 

그럼 서로 다른 타입도 가능할까요?....

다음을 쳐다보기로 하자 답이 나올 것이다​

@staticmethod
def returnMultiAnyVals():
    return 1,'2',False
 

결론은 된다는 것이다. 아래와 같이 호출한 측에서는 원하는 형식대로 즉, 서로 규약한 대로 받으면 될 것이다.

a1,b1,c1 = lib_tobee.TobeeStaticClass.returnMultiAnyVals()
print "여러다른 값 리턴이예요(%d,%s,%d) " % (a1, b1,c1)
 

3. 메인 함수에서 아규먼트 받기

처음에서 만들었던 getopt는 메인함수에서 아규먼트를 받는 것이었는 데 이 아규먼트를 받아서 특정 클래스에서 이를 처리 하도록 하고 싶다는 것이다.

가령 다음과 같이

a2,b2 = lib_tobee.TobeeStaticClass.parseArgs(args)
print "여러다른 값 리턴이예요(%d,%d) " % (a2, b2)
 

만들고 싶다는 거다. - Appendix B 참고

메서드 이름이 parseArgs로 선언 하였을 때,

@staticmethod
def parseArgs(mxd_args):
 

다음과 같이 구현 하였다.

@staticmethod
def parseArgs(mxd_args):
	print "[Conv] Main Start"

	if len(mxd_args) <= 1:
		print "not 'enough' arguments..."
		usage()

		return False,10001
	else:
		print "args size ==> [%d][%s]" % (len(mxd_args), mxd_args[0])

....중략

def usage():
	print __name__+".py -c [config file path] -m [mxd file path] [-v|-s]"
 

1. 잘은 돌아 갈것인가 묻는 다면? ... 물론 아니다 오류 메시지는

UnboundLocalError: local variable 'usage' referenced before assignment

2. 그래서 usage 메서드를 parseArgs 메서드 위해 선언 하였다.

그러면 이번에는 잘 돌았을까??.... 역시나....

NameError: global name 'usage' is not defined

이유야 잘 생각 해보면 알겠지만..뭐 굳이 생각하고 싶지 않다...

3. 그런 다음 usage 메서드를 static으로 한다.

@staticmethod
def usage():
... 생략
 

이번이 끝??....역시나

NameError: global name 'usage' is not defined

 

4. 소스 완성

그래서 이 모든 것을 견뎌내고 완성된 소스는 다음과 같다.

@staticmethod
def parseArgs(mxd_args):
	print "[Conv] Main Start"

	if len(mxd_args) <= 1:
		print "not 'enough' arguments..."
		TobeeStaticClass.usage()#<--- 여기
		return False,10001
	else:
		print "args size ==> [%d][%s]" % (len(mxd_args), mxd_args[0])

....중략

@staticmethod #<-- 여기
def usage():
	print __name__+".py -c [config file path] -m [mxd file path] [-v|-s]"
 

Appendix A:

TobeeStaticClass 클래스 소스

class TobeeStaticClass:
	message = ""

	def __init__(self, message): # 생성자 / 객체 생성시 호출.
		self.message = message

	@staticmethod
	def showMyMessage():
		print "정적 메서드 알지? "

	@staticmethod
	def returnMultiVals():
		return [1,2,3]

	@staticmethod
	def returnMultiAnyVals():
		return 1,'2',False

	@staticmethod
	def usage():
		print __name__+".py -c [config file path] -m [mxd file path] [-v|-s]"

	@staticmethod
	def parseArgs(mxd_args):
		print "[Mxd Conv] Main Start"

		if len(mxd_args) <= 1:
			print "not 'enough' arguments..."
			TobeeStaticClass.usage()
			return False,10001
		else:
			print "args size ==> [%d][%s]" % (len(mxd_args), mxd_args[0])

		print mxd_args[2]

		try:
			opts, mxd_args = getopt.getopt(mxd_args[1:], "c:m:hvs", ["config", "mxd", "help", "valcheck","start"])
		except getopt.GetoptError as err:
			# print help information and exit:
			print str(err) # will print something like "option -a not recognized"
			TobeeStaticClass.usage()
			return False,10002
		configpath = ""
		mxdpath = ""
		validationcheck = False
		start = False

		for o, a in opts:
			if o in ("-c", "--config"):
				configpath = a
				print a
			elif o in ("-m", "--mxd"):
				mxdpath = a
			elif o in ("-h", "--help"):
				usage()
				sys.exit()
			elif o in ("-v", "--valcheck"):
				validationcheck = True
			elif o in ("-s", "--start"):
				start = True
			else:
				assert False, "unhandled option"

		if start == True or validationcheck == True:
			print configpath
		else:
			TobeeStaticClass.usage()

		return False,10002

	def __del__(self): # 소멸자 / 객체 소멸시 호출
		message = None
 

Appendix B

메인 함수 소스

​​def main(args):
    a2,b2 = lib_tobee.TobeeStaticClass.parseArgs(args)
    print "여러다른 값 리턴이예요(%d,%d) " % (a2, b2)
 

출력결과

[Conv] Main Start
not 'enough' arguments...
com.tobee.lib_tobee.py -c [config file path] -m [mxd file path] [-v|-s]
여러다른 값 리턴이예요(0,10001)

 

 

 
728x90

'프로그래밍' 카테고리의 다른 글

[C/C++]sizeof 사용 없이 배열의 sizeof 찾기  (0) 2023.01.29
[C#] quartz 모듈 사용하기  (0) 2023.01.28
파이썬 사용해보기-4  (1) 2023.01.26
파이썬 사용해보기-3  (0) 2023.01.25
파이썬 사용해보기-2  (0) 2023.01.24