Microsoft MVP성태의 닷넷 이야기
스크립트: 61. 파이썬 - 함수 오버로딩 미지원 [링크 복사], [링크+제목 복사],
조회: 10713
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

파이썬 - 함수 오버로딩 미지원

파이썬은 (같은 이름의) 동일한 함수가 재정의(overload)된 경우 딱히 오류 메시지 없이 마지막에 정의한 함수 이름을 기준으로 처리합니다.

def do_func():
    print('do_func')


def do_func(arg=5):
    print('do_func:', arg)


do_func()
do_func(1)

""" 출력 결과
do_func: 5
do_func: 1
"""

위의 경우, 나중에 정의한 do_func(arg=5) 함수가 호출돼 동작을 한 건데요, 따라서 다음과 같이 순서를 바꾸는 경우에는,

def do_func(arg=5):
    print('do_func:', arg)


def do_func():
    print('do_func')


do_func()   # 정상 호출

do_func(1)  # 오류 발생
"""
Traceback (most recent call last):
  File "/work/test.py", line 11, in <module>
    do_func(1)
TypeError: do_func() takes 0 positional arguments but 1 was given
"""

나중에 정의한 "do_func()"를 유효한 함수로 처리하므로 "do_func(1)"로 호출했을 때 예외가 발생한 것입니다.




이런 규칙은 instance/static 함수에도 적용됩니다. 가령 다음과 같이 동일한 이름을 정의하면,

class MyType(object):

    @staticmethod
    def do_func(arg):  # 이후 동일한 이름의 함수가 정의되므로 무효
        print('static do_func')

    def do_func(self, arg):  # 유효
        print('instance do_func:', arg)


inst = MyType()

inst.do_func(6)  # 인스턴스 함수 호출 성공

MyType.do_func(5)  # [타입].[함수] 형식으로 호출하면 "self"를 전달하지 않으므로, 
                   # 전달한 "5" 값이 인스턴스 함수의 self에 매칭되고, 결국 argument 불일치로 에러 발생 - TypeError: MyType.do_func() missing 1 required positional argument: 'arg'

오류가 발생합니다. 반면 이렇게 정의하면,

class MyType(object):
    def do_func(self, arg):  # 무효
        print('instance do_func:', arg)

    @staticmethod
    def do_func(arg):  # 유효
        print('static do_func')


inst = MyType()
inst.do_func(6)  # 정적 함수 실행
MyType.do_func(5)  # 정적 함수 실행

""" 출력 결과
static do_func
static do_func
"""

오류는 발생하지 않지만 정적 함수가 호출되는 것이므로 자칫 인스턴스 함수가 정상 실행된 경우로 착각해 프로그램에 버그가 발생할 수 있습니다.

사실, 파이썬 입장에서는 class의 instance/static 함수에 대한 구분이 없습니다. 실제로 static 함수라고 표시하는 @staticmethod는 임의로 만들어진 decorator 클래스에 불과합니다. 게다가 더욱 근본적인 문제는, 파이썬은 모든 형식이 key/value에 불과한 dictionary 자료형으로 처리한다는 점입니다.

따라서 다음과 같은 식으로 코드를 수행하면,

import types


def test():
    print('test')


async def test(arg):
    print('test-async', arg)

item = None
func = None

for item in globals().keys():
    func = globals()[item]
    if isinstance(func, types.FunctionType) is False:
        continue
    print(func)

""" 출력 결과
test <function test at 0x7fe7303fdc60>
"""

화면에는 "test" 라인 하나만 출력되는 것을 확인할 수 있습니다. dictionary의 키 자체도 함수의 이름만 담고 있는 "str" 타입이어서 엄밀히 "def test()"와 "async def test()"가 모두 "test" 키를 공유하기 때문에 구분할 방법이 없는 것입니다.




이러한 제약은 동일한 이름의 함수와 클래스를 정의하는 것도 막게 됩니다.

def test():  # 이후에 정의한 같은 이름의 test 클래스로 인해 무효
    print('test')


class test(object):  # 마지막에 정의한 "test" 키의 값으로 class 타입 정의
    pass


v = test()  # 함수 호출과 클래스 인스턴스 생성의 구문이 동일
            # "test"라는 이름으로 마지막에 정의한 것이 class이므로 클래스의 개체 생성

print(v)    # 출력 결과 <[파일이름].test object at 0x7ff7d86816d0>

클래스 역시 module에 등록하는 키 값은 str 타입의 클래스 이름이기 때문에 기존의 함수를 덮어쓰는 것입니다. 이쯤 되면 눈치채셨겠지만, module의 __dict__에는 전역 변수, 함수, 클래스, 그 모듈에서 포함한 (import) 모듈 정보들이 모두 '이름' 키로 등록되기 때문에 그 모든 것들이 가장 나중에 정의한 것만 유효하게 됩니다.


import importlib


do_func = 'test'  # 변수 무효: 이후 do_func 함수가 정의되므로.


def do_func():   # 유효: 이전의 do_func 변수를 덮어씀.
    print('do-func')


module = importlib.import_module(__name__)

item = None
for item in module.__dict__.keys():
    if item == 'do_func':
        print(item, module.__dict__[item])

""" 출력 결과
do_func <function do_func at 0x7f00ba8ef100>
"""




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/1/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 76  77  78  79  80  81  82  83  84  [85]  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11842정성태3/13/201917172개발 환경 구성: 433. 마이크로소프트의 CoreCLR 프로파일러 예제를 Visual Studio CMake로 빌드하는 방법 [1]파일 다운로드1
11841정성태3/13/201917627VS.NET IDE: 132. Visual Studio 2019 - CMake의 컴파일러를 기본 g++에서 clang++로 변경
11840정성태3/13/201919673오류 유형: 526. 윈도우 10 Ubuntu App 환경에서는 USB 외장 하드 접근 불가
11839정성태3/12/201923702디버깅 기술: 124. .NET Core 웹 앱을 호스팅하는 Azure App Services의 프로세스 메모리 덤프 및 windbg 분석 개요 [3]
11838정성태3/7/201927445.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes [1]파일 다운로드1
11837정성태3/6/201941125기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201924789오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201922948.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201921639개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201922702개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917705오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201918473오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201917691오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201919004개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201927439개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919896오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201920419오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201926089개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201920345오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201921374오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201920509오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201921291오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201924402오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201923434Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201921522VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201917438오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
... 76  77  78  79  80  81  82  83  84  [85]  86  87  88  89  90  ...