Search

Method Override & Function Overload

카테고리
Programming
태그
Python
게시일
2024/08/05
수정일
2024/08/05 15:39
시리즈
python_syntax
1 more property

Fundamentals

override와 overload에 대한 개념을 먼저 알아보도록 하겠습니다.

Method(or Function) overriding

Method overriding, in object-oriented programming(OOP), is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
위의 Method overriding의 정의를 요약하면, 하위 클래스 또는 자식 클래스가 해당 부모(혹은 슈퍼)클래스에서 이미 제공한 Method를 재정의하여 사용할 수 있는 기능을 말합니다. “상위 클래스에서 정의한 메소드를 자식 클래스에서 변경” 하는 기능을 제공함으로써, 상속받아 작성한 코드의 자유도를 높혀줄 수 있는 좋은 기능입니다.
아래는 다양한 코드의 예시입니다.

Python

class Thought: def __init__(self) -> None: print("I'm a new object of type Thought!") def message(self) -> None: print("I feel like I am diagonally parked in a parallel universe.") class Advice(Thought): def __init__(self) -> None: super(Advice, self).__init__() def message(self) -> None: print("Warning: Dates in calendar are closer than they appear") super(Advice, self).message()
Python
복사

Java

class Thought { public void message() { System.out.println("I feel like I am diagonally parked in a parallel universe."); } } public class Advice extends Thought { @Override // @Override annotation in Java 5 is optional but helpful. public void message() { System.out.println("Warning: Dates in calendar are closer than they appear."); } }
Java
복사

Kotlin

fun main() { val p = Parent(5) val c = Child(6) p.myFun() c.myFun() } open class Parent(val a : Int) { open fun myFun() = println(a) } class Child(val b : Int) : Parent(b) { override fun myFun() = println("overrided method") }
Kotlin
복사

Method(or Function) overloading

function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.
위의 Function overloading은 method overloading이라고도 합니다. 위의 정의를 요약하면, 같은 이름의 여러 함수를 선언하여 사용할 수 있도록 하는 기능을 말합니다. Overload 된 함수에 대한 호출은 arguments를 어떻게 넣어주는지에 따라 다르게 호출할 수 있습니다.

C++

#include <iostream> int Volume(int s) { // Volume of a cube. return s * s * s; } double Volume(double r, int h) { // Volume of a cylinder. return 3.1415926 * r * r * static_cast<double>(h); } long Volume(long l, int b, int h) { // Volume of a cuboid. return l * b * h; } int main() { std::cout << Volume(10); std::cout << Volume(2.5, 8); std::cout << Volume(100l, 75, 15); }
C++
복사

Python

Python에는 오버로딩 기능을 정식으로 지원하지 않습니다. 다른 언어에서와 비슷하게 Overloading 코드를 작성해보면 다음과 같이 작성해볼 수 있겠습니다.
class TestClass(object): def __init__(self): pass def some_method(self, arg1, arg2): return arg1 + arg2 def some_method(self, arg1, arg2, arg3): return arg1 + arg2 + arg3 tc = TestClass() print(tc.some_method(1,2)) print(tc.some_method(1,2,3)) # TypeError: some_method() missing 1 required positional argument: 'arg3'
Python
복사
위와 같이 코드를 작성하게 되면 에러가 발생하게 됩니다. 이를 이해하기 위해서는 python 내장 함수인 locals()globals() 를 이용하여 확인해보는 방법으로 접근해볼 수 있습니다.
locals
locals 메소드를 디버깅 모드로 확인해보면, _method 라는 함수가 있다는 것을 알 수 있습니다. 만약 여기서 동일한 이름의 함수를 선언하였을 경우 locals에서 반환된 데이터는 하나의 메소드만을 반환하게 됩니다. 아래와 같은 예시를 통해 Python에서 overloading 을 사용할 수 없다는 것을 확인할 수 있습니다.
def _method(arg1, arg2): print(arg1 + arg2) a = locals() """ a { '__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe153e578b0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'Overload3.py', '__cached__': None, '_method': <function _method at 0x7fe153eb71f0> } """
Python
복사
globals
globals 메소드로 데이터를 디버깅 모드로 확인해보면 아래와 같은 구조를 확인할 수 있을 것입니다.
class TestClass(object): def __init__(self): pass def some_method(self, arg1, arg2): return arg1 + arg2 def some_method(self, arg1, arg2, arg3): return arg1 + arg2 + arg3 a = globals() """ a { '__name__': '__main__', '__doc__': None, '__package__': '', '__loader__': None, '__spec__': ... } > special variables > function variables > class variables > 'TestClass': <class '__main__.TestClass'> > special variables > function variables > some_method: <function TestClass.some_method at 0x7fbea5816040> .... """
Python
복사
단, 비슷한 동작 방식으로 구현은 가능합니다. 아래의 코드는 overloading의 목적에 맞추어 어떻게든 기능을 하게끔 만든 코드입니다. 하지만 Python을 사용하면서 아래와 같은 방법으로 코드를 작성할 때 굳이 저렇게 작성하고자 하지는 않을 것이라 생각됩니다.
class TestClass(object): def __init__(self): pass def some_method(self, arg1, arg2): if isinstance(arg1, int) and isinstance(arg2, int): return arg1 * arg2 elif isinstance(arg1, str) and isinstance(arg2, str): return f"String : {arg1} is {arg2}" tc = TestClass() print(tc.some_method(1,1)) print(tc.some_method("Apple", "Fruit")) # 1 # String : Apple is Fruit
Python
복사
파이썬에서도 overloading을 사용하는 대표적인 예로 Operator Overloading(연산자 오버로딩) 이 있습니다. 추후 이 내용도 학습해봐야 겠습니다.

References