본문 바로가기
🛠️Skill/Python

[Python] 클래스(class) / 인스턴스, 객체, self, super 이해하기

by Istj_eff 2022. 10. 5.

클래스(class)

✔️클래스(class) : 설계도
ex) 과자틀


✔️인스턴스(instance), 객체(Object) : 과자틀에 의해서 만들어진 과자

💡 클래스로 만든 객체를 인스턴스라고도 한다.
그렇다면 객체와 인스턴스의 차이는 무엇일까? 이렇게 생각해 보자.
a = Cookie() 이렇게 만든 a는 객체이다. 그리고 a 객체는 Cookie의 인스턴스이다.
즉 인스턴스라는 말은 특정 객체(a)가 어떤 클래스(Cookie)의 객체인지를 관계 위주로 설명할 때 사용한다.

✔️타입(type) : 문자열(sting)이 ‘str’이라는 타입을 갖는 클래스인것처럼, 우리가 선언하는 클래스의 이름이 타입이 된다.

✔️속성(attribute) : 클래스의 내부 변수

✔️메소드(method) : 클래스 내에서 선언된 함수


stae : 객체 내의 인자들이 갖는 값

 

self

  • self는 객체 자기 자신을 의미한다
  • 메소드를 정의할 때 처음 전달값은 반드시 self를 넣는다’
  • 메소드 내에서는 self.name과 같은 형태로 멤버변수를 사용
  • 객체를 통해 메소드를 호출할때 self 부분에 해당하는 전달값은 따로 명시하지 않는다.
class BlackBox:
	pass

b1 = BlackBox() # b1객체생성
b1.name = '까망이'
print(b1.name) # '까망이'출력
print(isinstance(b1, BlackBox)) # True출력
class BlackBox:
	def __init__ (self, name, price):
	self.name = name
	self.price = price

b1 = BlackBox('까망이',200000) # b1 객체
print(b1.name, b1.price)

b2 = BlackBow('하양이',100000) # b2 객체
print(b2.name, b2.price)
# 여행모드 지원 블랙박스
class TravelBlackBox:
	def __init__ (self, name, price):
	self.name = name
		self.price = price

	def set_travel_mode(self,min):
		print(f'{self.name} {min}분 동안 여행 모드 on')

b1.set_travel_mode(20)
=> 까망이 20분 동안 여행 모드 on

TravelBlackBox.set_travel_mode(b1,20)
=> 까망이 20분 동안 여행 모드 on

 

 

super()

  • 메소드 내에서 super()를 통해 부모 클래스의 메소드에 접근 할 수 있다.
class BlackBox:
	def __init__ (self, name, price):
	self.name = name
	self.price = pric

# 상속받은 여행모드 지원 블박에 용량을 선택할 수 있도록 추가하고싶다
class TravelBlackBox(BlackBox):
	def __init__ (self, name, price, sd):
	super().__init__(name,price) # 부모클래스인 BlackBox를 super로 불러옴
	self.sd = sd  # 추가된 sd만 지정

	def set_travel_mode(self,min):
		print(f'{self.name} {min}분 동안 여행 모드 on')

 

 

다중상속

class VideoMaker:
	def make(self)
		print('추억용 여행 영상 제작')

class TravelBlackBox(BlackBox, VideoMaker):
	def __init__ (self, name, price, sd):
	super().__init__(name,price) 
	self.sd = sd

	def set_travel_mode(self,min):
		print(f'{self.name} {min}분 동안 여행 모드 on')

b1 = TravelBlackBox('하양이',100000,64)
b1.make() # '추억용 여행 영상 제작' 출력

class MailSender:
	def send(self)
		print('메일 발송')

class TravelBlackBox(BlackBox, VideoMaker, MailSender):
	def __init__ (self, name, price, sd):
	super().__init__(name,price) 
	self.sd = sd

	def set_travel_mode(self,min):
		print(f'{self.name} {min}분 동안 여행 모드 on')

b1 = TravelBlackBox('하양이',100000,64)
b1.make() # '추억용 여행 영상 제작' 출력
b1.send() # '메일 발송' 출력

 

 

메소드 오버라이딩(overriding)

  • 자식 클래스에서 같은 메소드를 새로 정의하지 않으면, 부모 클래스의 메소드를 쓰게 된다.
  • 자식 클래스에서 같은 메소드를 새로 정의하면 자식 클래스의 메소드를 쓰는것이다.
# 자동으로 영상제작하고 메일까지 발송하는 클래스로 업그레이드하고싶다
class AdvancedTravelBlackBox(TravelBlackBox):
	def set_travel_mode(self,min):
		print(f'{self.name} {min}분 동안 여행 모드 on')
		self.make()
		self.send()

b2 = AdvancedTravelBlackBox('초록이',120000,64)
b2.set_travel_mode(15)

 

 


💡 클래스 계산기 예제

# 계산기 1개
result = 0

def add(num):
    global result
    result += num
    return result

print(add(3)) => 3
print(add(4)) => 7

# 계산기 2개가 필요하다면?
result1 = 0
result2 = 0

def add1(num):
    global result1
    result1 += num
    return result1

def add2(num):
    global result2
    result2 += num
    return result2

print(add1(3))
print(add1(4))
print(add2(3))
print(add2(7))

 

💡 계산기 예제 2

# 계산기가 더 많이 필요하다면? 클래스로 만들자!
class Calculator:
    def __init__(self):
        self.result = 0

    def add(self, num):
        self.result += num
        return self.result

		def sub(self, num):  # 빼기 기능도 추가
        self.result -= num
        return self.result

cal1 = Calculator() # cal1 객체
cal2 = Calculator() # cal2 객체

print(cal1.add(3))
print(cal1.add(4))
print(cal2.add(3))
print(cal2.add(7))

 

 

 

댓글