Language/Python

2021 - 04 - 18, Python 학습 - 모델링, 메소드

Cs.Woo 2021. 4. 18. 23:43

## 모델링

class Human():

    '''사람''' # Human 클래스 생성



# person = Human()  # person을 Human 클래스에 할당

# person.name = '철수' # person에 name이라는 attribute를 부여

# person.weight = 60.5 # person에 weight라는 attribute를 부여

 

# 매번 Human클래스를 사용할 때마다 상기의 코드를 입력하기엔 

# 비효율적임

 

# 따라서 name과 weight를 인자로 받는 함수를 생성한뒤

# 그 인자로 attribute를 생성하도록 설정

 

def create_human(name, weight):

    person = Human() # person을 Human 클래스에 할당

    person.name = name # create_human을 사용할때 매개변수로  받은것을 attribute로 부여

    person.weight = weight # create_human을 사용할때 매개변수로  받은것을 attribute로 부여

    return person # person을 리턴

 

Human.create = create_human # create_human 이라는 함수를 Human클래스의 create 라는 attribute로 할당함



person1 = Human.create('철수', 60.5)

print(person1.name, person1.weight)

 

def eat(person): # eat이라는 함수를 선언

    person.weight += 0.1 # person의 weight라는 attribute에 0.1을 더한 뒤 반환

    print("{}가 먹어서 {}kg이 되었습니다.".format(person.name,person.weight)) # 출력

 

def walk(person): # walk 라는 함수를 선언

    person.weight -= 0.1 #person의 weight 라는 attribute에 0.1을 뺀 후 반환

    print("{}가 걸어서 {}kg이 되었습니다.".format(person.name,person.weight # 출력

 

# 상기 함수들을 Human에 부여하기

 

Human.eat = eat  # eat함수를 Human클래스에 넣기

Human.walk = walk # walk함수를 Human클래스에 넣기

 

person.walk()

person.eat()

person.walk()



## 메소드

 

# 모델링의 예제에서 함수를 클래스 밖에서 선언하고 클래스에 지정해 준것을

# 클래스 안에서 선언하고 밖에서 쓸 수 있도록 할 수 있다.

# 이 때, 클래스 안에서 기능을 할 수 있게 하는 함수를 메소드라고 한다.

 

# 예제는 다음과 같다

 

class Human():

    '''인간'''

    def create(name,weight):

        person = Human()

        person.name = name

        person.weight = weight

        return person

 

    def eat(self):   #파이썬의 메소드의 첫번째 인자는 self 로 사용한다

        self.weight += 1

        print("{}가 먹어서 {}kg이 되었습니다.".format(self.name, self.weight))

    

    def walk(self):

        self.weight -= 1

        print("{}가 걸어서 {}kg이 되었습니다.".format(self.name, self.weight))

 

    def speak(self, message): # 인스턴스가 자동으로 첫번째 self로 들어간다. 그리고 인자 message를 받는다

        print("{}가 {} 라고 말했습니다.".format(self.name,message)) # 첫번째 포멧에는 create의 name이 들어가고 두번째에는 함수에서 받은 message 인자가 들어가게된다.

 

person = Human.create("철수",60.5)

 

person.eat()

person.walk()

person.speak("안녕하세요!")

 

## 정상구동 확인



## 특수한 메소드

 

class Human():

    '''인간'''

    def __init__(self, name, weight): # 클래스에 인스턴스를 만드는 순간 자동으로 실행되는 함수

        '''초기화 함수'''

        #매개변수를 받을 수도 있다.

        #print("__init__ 실행")

        self.name = name # init으로 create 함수를 대체할 수가 있다.

        self.weight = weight

        #print("이름은 {}, 몸무게는 {}".format(name, weight)) 

    

    #def __str__(self):

        '''문자열화 함수'''

        # 인스턴스 자체를 설명할 때 스트링으로 어떻게 표현될지가 나온다.

        # 인스턴스가 어떻게 문자열로 표현될지를 결정한다.

       return "{} (몸무게 {}kg)".format(self.name, self.weight)

 

#    def create(name,weight):

#        person = Human()

#        person.name = name

#        person.weight = weight

#        return person

 

    def eat(self):   #파이썬의 메소드의 첫번째 인자는 self 로 사용한다

        self.weight += 1

        print("{}가 먹어서 {}kg이 되었습니다.".format(self.name, self.weight))

    

    def walk(self):

        self.weight -= 1

        print("{}가 걸어서 {}kg이 되었습니다.".format(self.name, self.weight))

 

    def speak(self, message): # 인스턴스가 자동으로 첫번째 self로 들어간다. 그리고 인자 message를 받는다

        print("{}가 {} 라고 말했습니다.".format(self.name,message)) # 첫번째 포멧에는 create의 name이 들어가고 두번째에는 함수에서 받은 message 인자가 들어가게된다.

 

person = Human("사람", 60.5)

 

print(person.name) # init이라는 메소드로 인스턴스가 생성된 것을 확인

print(person.weight)

 

print(person) # str이 없으면 <__main__.Human object at 0x02036178> 처럼 설명없이 그 자체가 프린트되는데

# 사람 (몸무게 60.5kg)

# str로 정의를 해놓으면 정의된 값이 나온다