본문 바로가기
Language/Python

[Python] Main / class / 생성자 / return

by 별토끼. 2017. 8. 16.
반응형

[Python] Main / class / 생성자 / return


  • Main 이용하기
 
 * main
  - 05 : import를 하면 각 모듈이 적용된다.
  - 11 : __name__은 해당 모듈의 이름을 출력해준다.
  - 17 : 메인 메소드는 if __name__="__main__": 을 이용한다.
  - 19, 20 : 각 모듈의 메소드 이용


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#-*- coding: utf-8 -*-
 
# Step13_main.py
 
import MyModule, YourModule
print "----"
 
#print "MyModule.nick : ", MyModule.nick
#MyModule.printNick()
 
print "Step13_main.py __name__:", __name__
 
# 만일 main 으로 시작 되었을 때 실행할 코드가 있다면
# 아래와 같이 작성한다.
 
# java에서 main메소드 느낌
if __name__=="__main__":
    # main 으로 시작 되었을때만 실행순서가 들어온다.
    MyModule.printNick()
    YourModule.printNick()
cs


 * MyModule

1
2
3
4
5
6
7
8
9
10
#-*- coding: utf-8 -*-
 
print u"MyModule.py 에 실행순서가 들어 왔습니다"
 
nick="김구라"
 
def printNick():
    print "nick:", nick
    
print "MyModule __name__ :", __name__
cs


* YourModule

1
2
3
4
5
6
7
8
9
10
11
12
#-*- coding: utf-8 -*-
 
# YourModule.py
 
print u"YourModule.py 에 실행순서가 들어 왔습니다."
 
nick=u"원숭이"
 
def printNick():
    print "nick:", nick
    
print "YourModule __name__ :", __name__
cs


 * 출력 결과





  • Class 생성하기
 - 클래스 내부의 필드(속성, 저장소), 메소드(기능, 함수) 
 : 메소드는 def로 선언
def 함수명(입력 인수): <수행할 문장1> <수행할 문장2
...

[참조]https://wikidocs.net/24


 - self : 객체의 참조값이 전달된다.

 - 24 : car1 에 car클래스를 이용해 객체를 생성한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#-*- coding: utf-8 -*-
'''
    - 객체를 생성하기 위한 설계도 : class 정의하기
'''
 
# Car 클래스 정의하기
 
class Car:
    #필드(속성, 저장소)
    name=u"소나타"
    
    #메소드(기능, 함수)
    def drive(self):
        print u"달려요"
        
    #메소드
    def showInfo(self):
        # self 에는 객체의 참조값이 전달된다 
        print u"차의 이름:", self.name
        
 
if __name__ == '__main__':
    # Car 클래스를 이용해서 객체를 생성하고 참조값을 변수에 담기
    car1=Car()
    # Car 객체의 필드 참조해서 콘솔에 출력하기 
    print "car1.name :", car1.name
    # Car 객체의 메소드 호출하기
    car1.drive()
    car1.showInfo()
    # type 출력해보기
    print "car1 type:", type(car1)
    
 
cs


  • 생성자
 - 10 : __init__으로 생성자를 만들 수 있다.
 - 10 : 객체를 생성하면서 필드값을 받도록 한다.
 - 22, 23 : 생성과 동시에 생성자가 호출되며 console이 출력된다.
 - 25 : 메소드를 호출하면 저장되있던 필드 정보를 출력한다. 
 - 17 : 메소드를 호출하면 해당 메소드가 출력되는데 이 때 .format을 이용한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#-*- coding: utf-8 -*-
 
class Car:
    #필드 정의하기
    company=None #제조사
    name=None #이름
    color=None #색상
    
    #생성자
    def __init__(self, company, name, color):
        print u"__init() 생성자 호출됨"
        self.company=company
        self.name=name
        self.color=color
    #메소드
    def showInfo(self):
        info=u"제조사:{}, 이름:{}, 색상:{}"\
            .format(self.company, self.name, self.color)
        print info
 
if __name__ == '__main__':
    car1=Car(u"현대", u"소나타", u"검정색")
    car2=Car(u"기아", u"프라이드", u"은색")
    
    car1.showInfo()
    car2.showInfo()
cs



  • return 
 - 22 : getCoffee() 메소드로 Coffee객체를 생성해서 리턴해준다
 - 43 : 리턴받은 Coffee객체로 eat메소드를 호출한다.
 - 25 : 인자로 전달받은 수(amount)만큼 Coffee객체를 생성하고
    list type인 coffees에 담아서 리턴해준다.
 - 49 : myCoffees에 들어있는 coffee객체를 순서대로 호출한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#-*- coding: utf-8 -*-
 
'''
    가상의 Coffee 객체를 생성할 수 있는 클래스 정의
   가상의 Starbucks 객체를 생성할 수 있는 클래스 정의
'''
 
class Coffee:
    #커피를 먹는 메소드
    def eat(self):
        print u"얌얌"
class StarBucks:
    #필드
    branch=None #지점명을 저장할 필드
    #생성자
    def __init__(self, branch):
        # 인자로 전달된 지점명을 필드에 저장하는 code 작성
        self.branch=branch
    def showBranch(self):
        # 필드에 저장된 필드명을 콘솔에 출력하는 code 작성
        print u"지점명:",self.branch
    def getCoffee(self):
        # Coffee 객체를 생성해서 참조값을 리턴해주는 code 작성
        return Coffee()
    def getCoffees(self, amount):
        # 인자로 전달되는 int type 만큼 Coffee 객체를 생성해서
        # list type에 담아서 리턴해주는 code 작성
        coffees=[]
        for i in range(amount):
            coffees.append(Coffee())
        return coffees
 
if __name__ == '__main__':
    star1=StarBucks(u"구로지점")
    star2=StarBucks(u"종로지점")
    
    star1.showBranch()
    star2.showBranch()
    
    print "----------"
    
    # Coffee 객체 리턴받아서 eat() 메소드 호출
    star1.getCoffee().eat()
    # StarBucks 구로지점에서 Coffee 객체 5개를 list type으로 받기
    myCoffees=star1.getCoffees(5)
    print "------"
    # list type 에 들어있는 모든 coffee 객체의 메소드
    # 순서대로 호출하기
    for item in myCoffees:
        item.eat()
        
    print u"__main__ 의 실행 순서가 종료 됩니다."
cs





반응형

'Language > Python' 카테고리의 다른 글

[Python] Decorator  (0) 2017.08.16
[Python] Extends / super  (0) 2017.08.16
[Python] 정규표현식(Regulation Express) / input  (0) 2017.08.16
[Python] if / for / while / operator  (0) 2017.08.10
[Python] list / tuple / dict / set 이용하기  (0) 2017.08.10

댓글