파이썬 챌린지 5일차 TIL

seoyeon·2023년 3월 10일
0

UDR

목록 보기
5/42

클래스, 인스턴스

  • 클래스 : 객체를 만들어 내기 위한 설계도, 변수와 메서드의 집합
  • 인스턴스 : 설계도를 바탕으로 구현된 구체적인 실체, 메모리에 할당되에 실제 사용되는 값

사용 이유? : 코드를 파악하기 수월함
클래스에 함수를 넣을 수 있음

📝 instance

numbers1 = []
type(numbers1)
numbers2 = list(range(10))
numbers2
characters = list("hello")
print(numbers2, characters)

📝 make_class

class Human():
    '''사람'''
    
person1 = Human()
person2 = Human()

person1.language = '한국어'
person2.language = 'English'

print(person1.language)
print(person2.language)

person1.name = '서울시민'
person2.name = '인도인'

def speak(person):
    print("{}이 {}로 말을 합니다.".format(person.name, person.language))

Human.speak = speak

'''
speak(person1)
speak(person2)
'''
person1.speak()
person2.speak()

모델링

📝 class_modeling

class Human():
    '''인간'''

person = Human()
person.name = '철수'
person.weight = 60.5

def create_human(name, weight):
    person = Human()
    person.name = name
    person.weight = weight
    return person

Human.create = create_human

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

def eat(person):
    person.weight += 0.1
    print("{}가 먹어서 {}kg가 되었습니다.".format(person.name, person.weight))

def walk(person):
    person.weight -= 0.1
    print("{}가 걸어서 {}kg가 되었습니다.".format(person.name, person.weight))

Human.eat = eat
Human.walk = walk

person.walk()
person.eat()
person.walk()

메소드

  • 클래스 내에 함수 바로 작성 가능
  • 대체로 클래스의 첫번째 인자는 self로 선언
    → 이 경우 인스턴스가 자동으로 self로 들어가기에 값을 따로 입력하지 않아도 됌

📝 class_method

class Human():
    '''인간'''

    def create_human(name, weight):
        person = Human()
        person.name = name
        person.weight = weight
        return person

    def eat(self):
        person.weight += 0.1
        print("{}가 먹어서 {}kg가 되었습니다.".format(person.name, person.weight))

    def walk(self):
        person.weight -= 0.1
        print("{}가 걸어서 {}kg가 되었습니다.".format(person.name, person.weight))

    def speak(self, message):
        print(message)

Human.create = create_human

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

Human.eat = eat
Human.walk = walk

person.walk()
person.eat()
person.walk()

📸 강의 수강 목록 캡처

profile
안녕하세용

0개의 댓글

관련 채용 정보