프로그래밍/파이썬🐍

(7)점프투파이썬_[5-1파이썬 프로그래밍의 핵심, 클래스]

개발자 덕구🐾 2022. 1. 8. 20:00
728x90

귀엽고 쉽게 설명 잘되어있다. 

진짜 이지하고 재밌게 배울 수 있는 책이다. 

다만 언어를 배워 본 사람이 읽으면 약간 지루할 수 도 있다.

 

 

이야기형식을 클래스에 대해서 쉽게 설명되어있다. 

 

 

 

클래스 : 똑같은 무언가를 계속해서 만들 수 있는 설계 도면과 같다. [뽑기 틀]

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

 

 

 

클래스에 의해서 만들어진 객체를 인스턴스라고 한다. 

그렇다면 객체와 인스턴스의 차이점은??

 

jingu = Human()

Human이라는 클래스가 jingu라는 객체를 만든 코드이다. 

jingu는 객체이고 jingu라는 객체는 Human의 인스턴스이다. 

 

인스턴스는 객체가 어떤 클래스의 객체인지를 관계 위주로 설명할 때 사용된다. 

 

-> jingu는 객체, jingu는 Human의 인스턴스 라고 말한다. 

 

 

클래스의 함수에는 

 

class Service :
    secret = '오늘 금쪽이를 봤다.'
    def add (selt, a, b) :
        result = a+ b
        print('%d + %d = %d 입니다.' %(a,b,result))

pey = Service()

pey.add(5,7)

 

 

 

def add를 보면 알 수 있듯이 인수가 3개이다. 

그런데 pey.add(5,7)에서는 2개의 인수만을 넣고 호출하였다. 

 

그 이유는 pey가 Service의 인스턴스인지 확인을 해야하기때문에 

원래는 pey.add(pey,5,7) 와 같이 pey를 인자로 주어서 인스턴스 여부를 확인 해야하낟. 

 

하지만 이것은 너무 귀찮아서 self를 이용한다. 

 

self는 호출 시 이용한 인스턴스(여기서 pey)로 바뀐다.

그래서 pey.add(pey,5,7)  가 아닌 pey.add(5,7)  로 호출이 가능한것이다. 

 

 

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

 

 

pey = Service()  # 서비스 업체에 가입해서 pey라는 아이디를 얻음

 

 

이름을 불러주는 서비스를 시작 

-> 이름 설정이 필요

def setname 생성

 

class Service :
    secret = '오늘 금쪽이를 봤다.'
    def setname(self, name) :
        self.name = name 
    def add (self, a, b) :
        result = a+ b
        print('%s 님! %d + %d = %d 입니다.' %(self.name,a,b,result))

pey = Service()
pey.setname('python')
pey.add(5,7)

 

 

이름 설정(setname) 안하고 add를 하는 회원들이 계속 컨펌을 넣음 

 

__init__을 생각하게된다!

-> 인스턴스를 만들 때 항상 실행된다. 

즉, 아이디를 부여받을 때 항상 실행된다 .

 

그래서 pey = Service('홍길동') 과 같이 이름을 인스턴스를 만들면서 넣어주어야한다.

 

 

class Service :
    secret = '오늘 금쪽이를 봤다.'
    def __init__(self, name) :
        self.name = name 
    def add (self, a, b) :
        result = a+ b
        print('%s 님! %d + %d = %d 입니다.' %(self.name,a,b,result))

pey = Service('python')
pey.add(5,7)

__init__함수로 만드니 전보다 조금은 코드의 양이 줄었다. 

 

 


클래스 함수를 다른 말로 메서드(Method) 라고 한다. 

객체의 변수는 그 객체에서만 사용되는 값이다 .

 

 

<계산기 예제 >

 

 

class FourCal():
    def setnumber(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 mul(self) :
        result = self.first * self.second
        return result
    def div(self) :
        result = self.first / self.second
        return result

 

 

클래스의 상속

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

 

메서드 오버라이딩 

부모 클래스로부터 상속받은 함수와는 다르게 동작하도록 같은 이름으로 다르게 구현하는 것

 

 

연산자 오버로딩

연산자를 객체끼리 사용할 수 있게 하는 기법

'+'는 __add__

'-'는 __sub__ 등 다른 연산자들도 오버로딩이 가능하다. 

 

 

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 으로 %s 일 동안 여행을 가다.' %(self.fullname, where,day))

juliet = HouseKim('쥴리엣')
romio = HousePark('로미오')
juliet.travel('부산',4)
romio.travel('부산')
romio.love(juliet)
romio+juliet

 

나름의 러브스토리

 

[romio + juliet ]

객체끼리 '+' 연산을 하면 __add__ 메서드가 실행이 된다. 

 

여기서 싸우고 이혼한다는 이야기로 바꿔보도록 하겠다.

 

 

 

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 으로 %s 일 동안 여행을 가다.' %(self.fullname, where,day))

juliet = HouseKim('쥴리엣')
romio = HousePark('로미오')
juliet.travel('부산',4)
romio.travel('부산')
romio.love(juliet)
romio+juliet
romio.fight(juliet)
romio-juliet

 

반응형