2017년 6월 30일 금요일

Python Programming Basic(파이썬 프로그래밍 기본) 01 : 함수, 임포트, 클래스


개발환경 : Window8.1, Python3.4.2, PyCharm CommunityEdition(64)

(1)프로젝트 생성
<ASCII(Python2), UTF-8(Python3)은 인코딩 선언없이 사용가능>
인코딩을 원하는경우, #-*-coding:utf-8-*-

1. SimpleGame01.py (기본소스)
1
2
3
4
5
6
7
8
print("hello")
= input("Guess the number: ")
guess = int(g)
if guess == 5:
    print("YOU WIN!")
else:
    print("YOU LOSE!")
print("GAME OVER!")
cs
2. SimpleGame02.py ( SimpleGame01 + 함수사용)
   : 추가된 내용은 뒤에 #new line을 추가 해놓았음.
     단순히 1번의 소스를 def안으로 넣어주면 끝!

1
2
3
4
5
6
7
8
9
10
11
def guess_number(): #new line
    print("hello")
    g = input("Guess the number: ")
    guess = int(g)
    if guess == 5:
        print("YOU WIN!")
    else:
        print("YOU LOSE!")
    print("GAME OVER!")
guess_number()#new line
cs


3. SimpleGame03.py(SimpleGame02 + 메인함수사용)
   : 추가된 내용은 뒤에 #new line을 추가 해놓았음.
    단순히 2번 내용에서 함수를 부르고 있는 부분을 main thread를 생성하는 부분에 넣어주면, 끝!
     C나 Java를 배웠다면, void main(), public static void main(String []argv)부분과 같다고 생각하고 넘어가자!
1
2
3
4
5
6
7
8
9
10
11
12
def guess_number():
    print("hello")
    g = input("Guess the number: ")
    guess = int(g)
    if guess == 5:
        print("YOU WIN!")
    else:
        print("YOU LOSE!")
    print("GAME OVER!")
if __name__ == "__main__"#new line
    guess_number()
cs

4. SimpleGame04.py (임포트하여 사용하는 방법)
   : Lesson01 패키지안의 SimpleGame02파일안의 guess_number. 즉 함수를 import시키는 문장으로 다음을 실행하게되면, guess_number()를 두번 실행하게된다.
1
2
3
4
from Lesson01.SimpleGame02 import guess_number
guess_number()
cs

왜나하면,SimpleGame02파일안을 보면, 마지막에 guess_number()를 부르고 있기 때문이다. 

1
2
3
4
5
6
7
8
9
10
11
def guess_number(): #new line
    print("hello")
    g = input("Guess the number: ")
    guess = int(g)
    if guess == 5:
        print("YOU WIN!")
    else:
        print("YOU LOSE!")
    print("GAME OVER!")
guess_number()#new line
cs
하지만, SimpleGame03을 부르면 main안에서 부르고 있기 때문에 한 번 더 실행되지 않는다. 즉, main안에서 호출하고 있는 부분은 함께 호출되지 않는다.
만약, 다음과 같이 작성해서 두 번째와 같이 import만 한다면, def guess_number()밑에서 호출하고 있는 guess_number()를 실행하고 프로그램이 종료된다.
그렇다면 guess_number()를 호출해보자면, 오류가 발생한다. 
즉, SimpleGame03코드를 최초 한 번씩 실행하지만, main은 무시 + 최초 이후로는 guess_number2()만 사용할 수 있다.
왜냐하면, guess_number2()만 import했기 때문에!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def guess_number():
    print("hello")
    g = input("Guess the number: ")
    guess = int(g)
    if guess == 5:
        print("YOU WIN!")
    else:
        print("YOU LOSE!")
    print("GAME OVER!")
guess_number()
def guess_number2():
    print("hello2")
    g = input("Guess the number: ")
    guess = int(g)
    if guess == 5:
        print("YOU WIN!")
    else:
        print("YOU LOSE!")
    print("2GAME OVER!")
if __name__ == "__main__"#new line
    guess_number()
cs

1
from Lesson01.SimpleGame03 import guess_number2
cs
1
2
3
from Lesson01.SimpleGame03 import guess_number2
guess_number() #ERROR
cs

5. SimpleGame05.py(SimpleGame03 + 클래스사용)
클래스를 적용하여 소스를 작성하였다. 다음의 소스는 맞는걸까? 정답은 "틀렸다."
다음과 같은 오류가 발생한다.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ERROR SOURCE
class choose_numer():
    def guess_number(self):
        print("hello")
        g = input("Guess the number: ")
        guess = int(g)
        if guess == 5:
            print("YOU WIN!")
        else:
            print("YOU LOSE!")
        print("GAME OVER!")
if __name__ == "__main__"#new line
    choose_numer.guess_number()
cs

그렇다면, 어떻게 작성해야할까?

5-1. static method사용
     static method사용를 사용하면, self없이 같은 소스라도 실행이 가능하다.
     하지만, 추천하지 않는 방식이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class choose_numer():
    @staticmethod #new line
    def guess_number(): #new line
        print("hello")
        g = input("Guess the number: ")
        guess = int(g)
        if guess == 5:
            print("YOU WIN!")
        else:
            print("YOU LOSE!")
        print("GAME OVER!")
if __name__ == "__main__":
    choose_numer.guess_number()
cs

5-2. 클래스를 생성하고 부르는 방법사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class choose_numer():
    def guess_number(self):
        print("hello")
        g = input("Guess the number: ")
        guess = int(g)
        if guess == 5:
            print("YOU WIN!")
        else:
            print("YOU LOSE!")
        print("GAME OVER!")
if __name__ == "__main__"
    game = choose_numer() #new line
    game.guess_number() #new line
cs
위와 같이 간단히 def함수를 넣고 끝낼 수도 있지만, 처음 Python을 배우는 단계라면 class에 대해 좀 더 자세히 알아보자.

댓글 없음:

댓글 쓰기