당니이
다은이의 컴퓨터 공부
당니이
전체 방문자
오늘
어제
  • 분류 전체보기 (140)
    • Achieved 👩🏻 (14)
      • 생각들 (2)
      • TIL (6)
      • Trial and Error (1)
      • Inspiration ✨ (0)
      • 미국 박사 준비 🎓 (1)
    • Computer Vision💖 (39)
      • Basic (9)
      • Video (5)
      • Continual Learning (7)
      • Generative model (2)
      • Domain (DA & DG) (5)
      • Multimodal (8)
      • Multitask Learning (1)
      • Segmentation (1)
      • Colorization (1)
    • RL 🤖 (4)
    • Autonomous Driving 🚙 (11)
      • Geometry (4)
      • LiDAR 3D Detection (1)
      • Trajectory prediction (2)
      • Lane Detection (1)
      • HDmap (3)
    • Linux (15)
    • PyTorch👩🏻‍💻 (10)
    • Linear Algebra (2)
    • Python (5)
    • NLP (11)
      • Article 📑 (1)
    • Algorithms 💻 (22)
      • Basic (8)
      • BAEKJOON (8)
      • Programmers (2)
    • ML (1)
      • 통계적 머신러닝(20-2) (1)
    • SQL (3)
    • 기초금융 💵 (1)

블로그 메뉴

  • 홈
  • About me

공지사항

인기 글

태그

  • continual learning
  • Python
  • CL
  • Linux
  • NLP
  • Incremental Learning
  • 백준
  • 자료구조
  • domain generalization
  • 백트래킹
  • dfs
  • pytorch
  • 알고리즘
  • 리눅스
  • conda
  • til
  • domain adaptation
  • CV
  • LLM
  • 코딩테스트

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
당니이

다은이의 컴퓨터 공부

[Python] Python Class에 대한 기초 정리하기
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로 정의되는데, 흔히 method와 attribute로 구성된다고 생각하면 된다.

  • 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)
반응형
저작자표시 (새창열림)

'Python' 카테고리의 다른 글

[Python] 디렉토리 내 특정 파일 삭제하기  (0) 2022.10.11
[Python] 디버거 pdb 사용법 - 이 좋은걸 지금 알았다니..  (0) 2022.09.27
[Python] Segmentation label 시각화하기 - 픽셀 값이 너무 작을 때  (1) 2022.09.05
[Python] shutil과 os로 디렉토리, 폴더 조작하기  (0) 2022.08.05
    'Python' 카테고리의 다른 글
    • [Python] 디렉토리 내 특정 파일 삭제하기
    • [Python] 디버거 pdb 사용법 - 이 좋은걸 지금 알았다니..
    • [Python] Segmentation label 시각화하기 - 픽셀 값이 너무 작을 때
    • [Python] shutil과 os로 디렉토리, 폴더 조작하기
    당니이
    당니이
    씩씩하게 공부하기 📚💻

    티스토리툴바