클래스 개념

클래스

     무엇인가를 계속해서 만들어낼 수 있는 설계 도면

     별모양, 하트모양같은 뽑기의 틀

인스턴스

     클래스에 의해서 만들어진 피조물

     별 또는 하트가 찍힌 뽑기

 

# 클래스의 가장 간단한 예
class Simple:
    pass

# Simple 클래스의 인스턴스
a = Simple()



 

이야기 형식으로 클래스 기초 쌓기

클래스 변수

class Service:
    secret = "영구는 배꼽이 두 개다."

pey = Service()

pey.secret
>>> "영구는 배꼽이 두 개다."

클래스 함수

class Service :
    secret = "영구는 배꼽이 두 개다."    <- 유용한 정보
    def sum(self, a, b):    <- 더하기 서비스
        result = a + b
        print("%s + %s = %s입니다." % (a, b, result))

pey = Service()

pey.sum(1, 1)
>>> 1 + 1 = 2입니다.

self 간단히 살펴보기

class Service :
    secret = "영구는 배꼽이 두 개다."
    def sum(self, a, b):
        result = a + b
        print("%s + %s = %s입니다." % (a, b, result))

pey = Service()

pey.sum(1, 1)
>>> 1 + 1 = 2입니다.

더하기 서비스에 가입했는지 여부를 확인하기 위한 장치 추가

sum 함수의 첫 번째 입력값을 통해 가입 여부를 판단

pey라는 아이디를 가진 사람은 다음 처럼 sum 함수를 사용

pey.sum(pey, 1, 1)

sum 함수는 첫 번째 입력값을 가지고 가입한 사람인지 아닌지를 판단

따라서 첫 번째 입력 인수로 pey라는 아이디를 주면 sum 함수는 pey라는 아이디가 이미 가입되어 있는 것을 확인한 후 서비스를 제공해 줄 것이다.

 

클래스 내 함수의 첫 번째 인수는 무조건 self로 사용해야 인스턴스의 함수로 사용할 수 있다.

 

self 제대로 알기

사용자에게 이름을 입력받아서 더하기 서비스를 제공할 때 앞 부분에 그 이름을 넣어주기

class Service :
    secret = "영구는 배꼽이 두 개다."    
    def setname(self, name):
        self.name = name
    def sum(self, a, b): 
        result = a + b
        print("%s님 %s + %s = %s입니다." % (self.name, a, b, result))

pey = Service()

pey.setname("홍길동")

pey.sum(1, 1)
>>> 홍길동님 1 + 1 = 2입니다.

__init__이란 무엇인가?

아이디를 부여해 줄 때 사람의 이름을 입력받아야만 아이디를 부여해 해주는 방식으로 바꾸기

"인스턴스를 만들 때 항상 실행된다"

class Service :
    secret = "영구는 배꼽이 두 개다."    
    def __init__(self, name):
        self.name = name
    def sum(self, a, b): 
        result = a + b
        print("%s님 %s + %s = %s입니다." % (self.name, a, b, result))

pey = Service("홍길동")

pey.sum(1, 1)
>>> 홍길동님 1 + 1 = 2입니다.

클래스 자세히 알기

클래스란 인스턴스를 만들어내는 공장

클래스는 해당 인스턴스의 설계도라고 할 수 있음

클래스의 구조

class 클래스 이름[(상속 클래스명)]:
    <클래스 변수1>
    <클래스 변수2>
    ...
    <클래스 변수N>
    def 클래스 함수 1(self[, 인수1, 인수2, ...]):
        <수행할 문장1>
        <수행할 문장2>
        ...
    def 클래스 함수 2(self[, 인수1, 인수2, ...]):
        <수행할 문장1>
        <수행할 문장2>
        ...
    def 클래스 함수 N(self[, 인수1, 인수2, ...]):
        <수행할 문장1>
        <수행할 문장2>
        ...
    ...

class라는 키워드는 클래스를 만들 때 사용되는 예약어, 그 바로 뒤에 클래스 이름을 입력해야 한다.

클래스 이름 뒤에 상속할 클래스가 있다면 괄호() 안에 상속할 클래스 이름을 입력한다.

클래스 내부에는 클래스 변수와 클래스 함수들이 있다.

 

사칙연산 클래스 만들기

클래스를 어떻게 만들지 먼저 구상하기

  • 사칙연산 클래스 FourCal
  • 사칙연산을 하려면 두 숫자를 입력받아야겠군 setdata 메서드
  • 더하기 기능 sum 메서드
  • 빼기 기능 sub 메서드
  • 나누기 기능 div 메서드
  • 곱하기 기능 mul 메서드

클래스 만들기

class FourCal:
    def setdata(self, first, second):
        self.first = first
        self.second = second
    def sum(self):
        result = self.first + self.second
        return result
    def sub(self):
        result = self.first - self.second
        return result
    def div(self):
        result = self.first / self.second
        return result
    def mul(self):
        result = self.first * self.second
        return result

'박씨네 집' 클래스 만들기

클래스 구상하기

  • '박씨네 집 ' 클래스 HousePark
  • 박씨 가족의 '이름'을 설정하려면? setname 메서드 -> __init__메서드
  • 박씨 가족 중 한 사람이 여행 가고 싶은 곳을 출력해 볼까? travel 메서드

클래스 만들기

class HousePark:
    lastname = "박"
    #def setname(self, name):
    #    self.fullname = self.lastname + name
    def __init__(self, name):
        self.fullname = self.lastname + name
    def travel(self, where):
        print("%s, %s여행을 가다." %( self.fullname, where))

>>>pey = HousePark("응용")
>>>pey.travel("태국")
박응용, 태국여행을 가다.

클래스의 상속

어떤 클래스를 만들 때 다른 클래스의 기능을 물려받을 수 있게 만드는 것

class 상속받을 클래스명(상속할 클래스명)

 

'김씨네 집'이라는 HouseKim을 만들어보자

HouseKim이라는 클래스가 HousePark 클래스를 상속받는 예제

class HouseKim(HousePark):
    lastname="김"

>>>juliet = HouseKim("줄리엣")
>>>juliet.travel("독도")
김줄리엣, 독도여행을 가다.

메서드 오버라이딩

class HouseKim(HousePark):
    lastname="김"
    def travel(self, where, day):
        print("%s, %s여행을 %d일 가네." %( self.fullname, where, day))

>>>juliet = HouseKim("줄리엣")
>>>juliet.travel("독도", 3)
김줄리엣, 독도여행을 3일 가네.

연산자 오버로딩

연산자 오버로딩이란 연산자(+, -, *, /, ...)를 객체끼리 사용할 수 있게 하는 기법

class HousePark:
    lastname = "박"
    def __init__(self, name):
        self.fullname = self.lastname + name
    def travel(self, where):
        print("%s, %s여행을 가다." %(self.fullname, where))
    def love(self, other):
        print("%s, %s 사랑에 빠졌네" %(self.fullname, other.fullname))
    def __add__(self, other):
        print("%s, %s 결혼했네" %(self.fullname, other.fullname))

class HouseKim(HousePark):
    lastname="김"
    def travel(self, where, day):
        print("%s, %s여행을 %d일 가네." %( self.fullname, where, day))

>>>pey = HousePark("응용")
>>>juliet = HouseKime("줄리엣")
>>>pey.love(juliet)
>>>pey + juliet
박응용, 김줄리엣 사랑에 빠졌네
박응용, 김줄리엣 결혼했네

'박씨네 집' 클래스 완성하기

class HousePark: lastname ="박"
    def __init__(self, name):
        self.fullname = self.lastname + name
    def travel(self, where):
        print("%s %s여행을 가다." %(self.fullname, where))
    def love(self, other):
        print("%s, %s 사랑에 빠졌네"%(self.fullname, other.fullname))
    def __add__(self, other):
        print("%s, %s 결혼했네"%(self.fullname, other.fullname))
    def fight(self, other):
        print("%s, %s 싸우네"%(self.fullname, other.fullname))
    def __sub__(self, other):
        print("%s, %s 이혼했네"%(self.fullname, other.fullname))

class HouseKim(HousePark):
    lastname = "김"
    def travel(self, where, day):
        print("%s %s여행 %d일 가네." %(self.fullname, where, day))

pey = HousePark("응용")
juliet = HouseKim("줄리엣")
pey.travel("부산")
juliet.travel("부산",3)
pey.love(juliet)
pey + juliet
pey.fight(juliet)
pey - juliet

>>>박응용 부산여행을 가다.
>>>김줄리엣 부산여행 3일 가네.
>>>박응용, 김줄리엣 사랑에 빠졌네
>>>박응용, 김줄리엣 결혼했네
>>>박응용, 김줄리엣 싸우네
>>>박응용, 김줄리엣 이혼했네

'Python > 공부' 카테고리의 다른 글

파이썬 n진수 변환  (0) 2023.01.07
파이썬 최대공약수, 최소공배수 함수 - gcd, lcm  (2) 2023.01.05
입력  (0) 2022.12.31
리스트 컴프리헨션  (0) 2022.12.31
Python 내장함수 - enumerate  (0) 2022.03.23

+ Recent posts