[파이썬] 개념정리/[파이썬] 구문,문법정리

[Python] 객체지향 문법 (class와 object)

숨겨진 오징어 2020. 7. 8. 05:12

[Python] 객체지향 문법 (class와 object)


1. Class 선언 & attributes추가

1.1. 총 4개의 attributes (Mon, Tue, Wed, Thu)를 넣어주었다.

월요일은 가슴운동, 화요일은 등운동, 수요일은 하체운동, 목요일은 하체운동 하는 날로 루틴을 짰다.

 

Input:

class Routine():
    Mon = '가슴'
    Tue = '등'
    Wed = '하체'
    Thu = '어깨'
    
    
R1 = Routine()
R1

Output:

<__main__.Routine at 0x7fb0490780f0>
  • R1이라는 Routine()객체가 생성되었음을 알 수 있다.

 

1.2. 어떤 atrributes와 method를 가지는지 확인하는 함수 dir()을 적용하였다.

Input:

dir(R1)

Output:

['Mon',
 'Thu',
 'Tue',
 'Wed',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
  • 객체의 attributes를 확인해 볼 수 있었다. 다음은 Mon, Wed 속성들(attributes)에 접근해보자.

 

 

1.3. 객체의 attributes에 접근하였다.

Input:

print(R1.Mon)
print(R1.Wed)

Output:

가슴
하체

 

1.4. 객체의 attributes에 값을 대치해줄 수 있다.

Input:

R1 = Routine()
R2 = Routine()

R2.Mon = '이두삼두'

print(f'R1의 Monday에는 {R1.Mon}')
print(f'R2의 Monday에는 {R2.Mon}')

Output:

R1의 Monday에는 가슴
R2의 Monday에는 이두삼두

 

 

2. Class 객체의 method

2.1. Class 선언 & 메소드(method) 추가

※ 주의해야할 점 : 파이썬 Class 내의 method를 작성할 때, 항상 첫 번째 파라미터로 self를 사용해줘야 한다.

 

다음은 헬스장 한달 회비(cost)를 설정하는 set_cost 메소드, 헬스장 등록개월 수(month)를 설정하는 set_month 메소드를 추가한 예시다.

Input:

class Routine():
    Mon = '가슴'
    Tue = '등'
    Wed = '하체'
    Thu = '어깨'

    month=0
    cost=0

    def set_cost(self,cost):
        self.cost = cost
    
    def set_month(self,month):
        self.month = month

    def total_cost(self):
        return self.month * self.cost

R = Routine()
dir(R)

Output:

['Mon',
 'Thu',
 'Tue',
 'Wed',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'cost',
 'month',
 'set_cost',
 'set_month',
 'total_cost']

 

2.2. Class 선언 & 메소드(method) 호출

  • set_cost 메소드 호출

Input:

R.set_cost(cost = 5)
R.cost

Output:

5

 

  • set_month 메소드 호출

Input:

R.set_month(month = 12)
R.month

Output:

12

 

  • 위에서 언급했던 self를 첫번째 파라미터로 지정해야하는 이유는 다음 그림을 보면 쉽게 이해할 수 있다.
  • set_cost이건 set_month이건 메소드를 호출시, 다음 그림과 같이 객체 자신이 self로 할당되기 때문이다.
  • self 파라미터 지정이 없다면 메소드 호출시 에러가 발생한다.

 

 

  • total_cost 메소드 호출

Input:

print(f'{R.month}개월 헬스장 회비는 {R.total_cost()}만원이다')

Output:

12개월 헬스장 회비는 60만원이다