본문 바로가기
Python

[Python] overloading, overriding, and special methods

by ds31x 2023. 7. 13.

일반적인 Overloading

overloading (or over-load, 과적?)이란 같은 이름의 function, method, operator를 여러 개로 중복 정의하는 것을 가르킴.

  • function의 경우, call시 입력되는 arguments가 할당될 parameters를 다르게 하여 같은 이름의 여러 function 중에서 어느 것이 call된 것인지 구분이 가능함.
  • method의 경우도 arguments를 다르게 하면 역시 구분이 가능함.
  • operator의 경우, Python에선 special method를 이용하여 overloading이 이루어지는데, 이는 operand 에 해당하는 object들의 type에 따라 구분이 가능해진다.

주의할 것은 어떤 언어에서도 return value의 type만으로는 구분이 안되기 때문return value만 다르면서 name 및 parameters등이 같은 function은 중복으로 만들 수 없음.

overloading을 위해선,
method나 function의 선언문 또는 signature (java용어)가 달라야 한다고도 애기함.

하지만 Python에서는 function overloadingmethod overloading을 지원하지 않는다. (C, C++, Java와의 차이점)

같은 이름의 function 및 method는 자신이 속한 namespace 내에서 하나만 존재하게 되기 때문에 마지막에 정의해준 function과 method만이 동작하게 됨.

https://gist.github.com/dsaint31x/6c95d9c48c28a39210ed2ae14af5c276

 

py_func_method_overloading_not_supported.ipynb

py_func_method_overloading_not_supported.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com


Overriding과의 차이

overriding (or override)과 구분이 되는데, overriding

super class의 method에 대해

똑같은 name과 arguments를 유지(같은 signature)하면서

내부 구현을 재정의하는 것을 의미함.

  • 호출하는 object가 어느 class이냐에 따라 같은 signature인 method의 동작이 결정된다.

https://dsaint31.me/mkdocs_site/python/oop/oop_1_03_inheritance/#class-hierarchy

 

BME228

Inheritance (상속) OOP에서 애용되는 Object간의 관계(relation) 중의 하나이다. Inheritance를 통해 생성되는 관계가 is-a관계 (이후 다룸)임. Heirarchy(계층화)와 함께 modularity (모듈화)와 코드의 재사용성을

dsaint31.me


Operator Overloading과 Special Method Overriding

재미있는 것은 Python에서 operator overloading실제로 operand에 해당하는 object들의 class의 special methods를 override하여 구현한다. (operator overload를 위해 special method override를 수행)

  • 특정 object들이 같은지를 나타내는 ==연산을 overload하기 위해선 해당 object들의 class의 special method __eq__ 메소드를 override하면 된다.
  • 이 경우, 해당 class 의 object들에 대해 == operator가 동작할 때 __eq__ special method가 호출된다.

 

예를 들어 단어를 추상화한 dsWord라는 클래스의 a,b 객체가 있을 시,

두 객체가 같은 단어인지를 확인하는 __eq__ speical method를 dsWord라는 클래스에 override해 놓을 경우

a == b 로도 확인할 수 있게 됨.

 

2023.07.13 - [Python] - [Python] special methods and operator overloading

 

[Python] special methods

Python interpreter에 의해 간접적으로 호출되는 methods를 가르킴. 특징으로 double underscore __ 로 이름이 시작되고 끝난다. double underscore로 싸여있는 이름은 Python이 다른 syntax와 연결되어 사용되도록 미

ds31x.tistory.com

 

반응형

'Python' 카테고리의 다른 글

[Python] first-class object (일급객체)  (0) 2023.07.15
[Python] Callback function  (0) 2023.07.13
[Python] special methods and operator overloading  (0) 2023.07.13
[Python] list (sequence type) : summary  (0) 2023.07.12
[Python] set and frozenset  (0) 2023.07.12