본문 바로가기
Python/Python

클래스(Class), 메서드(method), 인스턴스(Instance), 객체(Object), self

by Sondho 2020. 4. 6.
  • function과 method의 차이

# function
def function_변수명():
...

# 메서드(method)
class 클래스_변수명():
  ...
  def 메서드_변수명():
    ...

 

  • 기본 형태

일반 함수와는 달리 메서드의 첫 번째 매개변수(argument) self는 특별한 의미를 가진다.

메서드의 첫 번째 매개변수 self를 명시적으로 구현하는 것은 파이썬만의 독특한 특징이다.

 

class 클래스_변수명():
  ...
    
  def 메서드_변수명(self): # method의 첫 argument(매개변수)는 method를 호출하는 instance 자신
    ...

인스턴스_변수명 = 클래스_변수명()
인스턴스_변수명.메소드_변수명()

 

 

아래처럼 그냥 호출했을 경우,

오류 문구에 start()에 매개변수(arguments)는 없는데 한 개를 받았다고 출력된다.

 

+) 객체와 인스턴스의 차이

porche는 객체이다.

porche객체는 Car()의 인스턴스이다.

# 예제1
class Car():
  wheel = 4
    
  def start(): # 첫 번째 매개변수가 자동으로 들어오지만 설정되어있지 않음.
    print("I started")
        
porche = Car()
porche.start()
# 예제1 실행결과

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    porche.start()
TypeError: start() takes 0 positional arguments but 1 was given
# 예제2
class Car():
  wheel = 4
    
    
  def start(self): # self에는 porche 자신이 들어오게 됨.
    print(self.color) # 즉, print(porche.color)와 똑같은 말이다.
    print("I started")
        
porche = Car()
porche.color = "Red Sexy Red"
porche.start()
# 예제2 실행결과
Red Sexy Red
I started
# 예제3
class Car():
  wheel = 4
    
    
  def start(self): # self에는 porche 자신이 들어오게 됨.
    print(self.color) # porche.color가 없음.
    print("I started")
        
porche = Car()
porche.start() # 호출을 했지만 self.color 즉, porche.color가 선언되지 않았다.
porche.color = "Red Sexy Red"
# 예제3 실행결과
Traceback (most recent call last):
  File "main.py", line 12, in <module>
    porche.start()
  File "main.py", line 8, in start
    print(self.color)
AttributeError: 'Car' object has no attribute 'color'

 

 

참고 : https://wikidocs.net/28

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

 

댓글