Microsoft MVP성태의 닷넷 이야기
스크립트: 61. 파이썬 - 함수 오버로딩 미지원 [링크 복사], [링크+제목 복사],
조회: 10697
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12421정성태11/19/202016068.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202016635오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202016930VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202019078오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202017506오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202018670오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202018201.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202020968VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202019618.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202021648.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202018226오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202019047디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202020703.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202035743도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202020809.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202021769.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202020300.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202020872.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018977.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202021203.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202020476VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202016497오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202019612.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202019752오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202019857.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202016232VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...