Python

[Python] Python Class에 대한 기초 정리하기

당니이 2023. 6. 11. 23:17
반응형

절대 내일 객체지향 시험이라서 쓰는 포스팅 아님

지금까지 계속 공부 해야지 해야지 했던 객체지향에 대한 내용을 포스팅 해보겠다 ! :3


 

# Python의 Class

Python에서 Class는 user-defined abstract data type이라고 볼 수 있다. 여기서 Abstract Data Type(ADT)(1) Encapsulation(2) Information hiding을 만족하는 객체의 class를 일컫는다. 각각을 자세히 이론적으로 알아보자면 다음과 같다.

  • Encapsulation : 절차지향언어들과 달리 data type declaration과 operation이 함께 제공되는 것
  • Information hiding : 알고리즘과 데이터에 대한 detail을 굳이 제공하지 않는 것 (=Abstraction)

이렇게 이론적으로 정의되는 class는 set of members로 정의되는데, 흔히 methodattribute로 구성된다고 생각하면 된다.

  • Member functions : for methods of object
  • Member variables : for attributes of object

위에서 정의되는 members는 우리가 잘 아는 것처럼 (object).(methods) 로 access 할 수 있다. 이런 class 개념을 간단히 구현해보면 아래와 같다.

class Score : 
  math = 0 
  science = 0 

  # 이 setscore가 생성자의 역할을 함 
  def setscore(self, m, s) :      # self : Object itself hidden argument
    self.math = m
    self.science = s

  def score(self) : 
    return self.math + self.science
a = Score()
a.setscore(10, 20)
print(a.score())

a.math = 70       # update 가능 
a.science = 80
print(a.score())

특히 주의해야할 사항은 member에는 public/private member가 존재한다는 것인데, 이는 아래와 같다.

  • Public member : class 정의 밖에서도 접근 가능
  • Private member : class 정의 밖에서는 접근 불가

Python에서 모든 member는 public하지만, access control은 naming을 통해 implicitly하게 이루어지도록 할 수 있다. 여기서 naming이라는 것은 __ (더블 언더바)로 시작하는 함수들은 private 하다고 보통 여겨진다. 따라서 이런 private member들은 directly하게 이용하지 않도록 주의해줘야 한다.

# __로 시작하는 private member(=hidden function)를 directly하게 쓰지 않도록 주의하기 !! (사용은 되지만 bad usage)
a.__init__(55, 66)
print(a.math, a.science)

 

# Object creation & deletion

위 class에서 object를 생성하고, 제거할 때는 pre-defined hidden member function을 통해 시작해준다. 여기서 hidden funtion이란 __(언더바 2개)로 시작하는 + 외부에서 접근이 안되는 private function을 일컫는다.

  • 생성 : __init__(self, var1 , var2, ...) 이용
  • 삭제 : __del__(self) 이용

특히 생성시에는 user에 의해 생성자로 생성되고, 삭제는 생성자로 다른 변수를 할당하게 되면 implicit 하게 이루어지는 편이다. 코드로 적용해보면 아래와 같다.

# Object creation & deletion :: start in pre-defined hidden member function 
class Score : 
  math = 0 
  science = 0 

  def __init__(self, m, s) :             # 생성자 > class 호출 시 생성자가 요구하는 args 넣어주기 !! 
    print('A score object is created')
    self.math = m
    self.science = s

  def __del__(self) :     # class를 다른 변수로 재할당하면 자연스럽게(implicit하게) 사라짐 
    print('A score object is deleted')

  def score(self) : 
    return self.math + self.science
a = Score(40, 60)
print(a.score())

a = Score(60, 80)      # 재할당하면 사라짐 
print(a.score())

"""
A score object is created
100
A score object is created
A score object is deleted
140
"""

 


 

# Operation Overloading

Python class에는 기본적으로 제공되는 operation private member 들이 존재하지만, 이들을 over-ridding 할 수 있다.

# Operation Overloading : 연산 redefine하기 
class Score : 
  score = 0 

  def __init__(self, s) : 
    self.score = s

  def __add__(self, other) :   # add 결과는 score 변수에 저장됨 
    return Score(self.score + other.score)

 


 

# Inheritance

상속은 OOP의 꽃인데, OOP 언어가 reuseable 할 수 있게 만들어주는 가장 중요한 부분이다. 특히 부모 클래스의 method를 그대로 가져와 쓸 수도 있고 새로운 method나 객체를 만들 수도 있다. 부모 클래스의 생성자를 불러올 때는 super().\_\_init\_\_(parentvar1, parentvar2, ..) 을 자식 클래스 생성자 안에 써주는걸 잊지 말자 !!

# Inheritance
class Person : 
  def __init__(self, first='', last='') : 
    self.first = first 
    self.last = last 

  def fullname(self) : 
    return self.first + ' ' + self.last 

class student(Person) :     # 위 person class를 상속한다 
  pass                      # 아무것도 안하고 pass하고 싶을 때 

# reusability를 위한 상속 
class student1(Person) : 
  def fullname(self) : 
    return 'Mr/Ms. ' + self.first + self.last     # fullname function override 

class student2(Person) : 
  def __init__(self, first, last, score) :       # 부모클래스 생성자에 score 추가 
    super().__init__(first, last)                # super().__init__ : 부모 클래스에서 온 생성자들 표시 
    self.score = score                           # 추가된 객체만 따로 써주깅 

  def name_with_score(self) : 
    return self.first + ' ' + str(self.score)
반응형