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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11463정성태3/15/201820287.NET Framework: 733. 스레드 간의 read/write 시에도 lock이 필요 없는 경우파일 다운로드1
11462정성태3/14/201823883개발 환경 구성: 354. HTTPS 호출에 대한 TLS 설정 확인하는 방법 [1]
11461정성태3/13/201826229오류 유형: 454. 윈도우 업데이트 설치 오류 - 0x800705b4 [1]
11460정성태3/13/201818338디버깅 기술: 112. windbg - 닷넷 메모리 덤프에서 전역 객체의 내용을 조사하는 방법
11459정성태3/13/201819566오류 유형: 453. Debug Diagnostic Tool에서 mscordacwks.dll을 찾지 못하는 문제
11458정성태2/21/201820472오류 유형: 452. This share requires the obsolete SMB1 protocol, which is unsafe and could expose your system to attack. [1]
11457정성태2/17/201824623.NET Framework: 732. C# - Task.ContinueWith 설명 [1]파일 다운로드1
11456정성태2/17/201830713.NET Framework: 731. C# - await을 Task 타입이 아닌 사용자 정의 타입에 적용하는 방법 [7]파일 다운로드1
11455정성태2/17/201819938오류 유형: 451. ASP.NET Core - An error occurred during the compilation of a resource required to process this request.
11454정성태2/12/201828898기타: 71. 만료된 Office 제품 키를 변경하는 방법
11453정성태1/31/201820701오류 유형: 450. Azure Cloud Services(classic) 배포 시 "Certificate with thumbprint ... doesn't exist." 오류 발생
11452정성태1/31/201826091기타: 70. 재현 가능한 최소한의 예제 프로젝트란? [3]파일 다운로드1
11451정성태1/24/201819905디버깅 기술: 111. windbg - x86 메모리 덤프 분석 시 닷넷 메서드의 호출 인자 값 확인
11450정성태1/24/201836164Windows: 146. PowerShell로 원격 프로세스(EXE, BAT) 실행하는 방법 [1]
11449정성태1/23/201822817오류 유형: 449. 단위 테스트 - Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.VideoRecorderEngine' or one of its dependencies. [1]
11448정성태1/20/201820903오류 유형: 448. Fakes를 포함한 단위 테스트 프로젝트를 빌드 시 CS0619 관련 오류 발생
11447정성태1/20/201822193.NET Framework: 730. dotnet user-secrets 명령어 [2]파일 다운로드1
11446정성태1/20/201822508.NET Framework: 729. windbg로 살펴보는 GC heap의 Segment 구조 [2]파일 다운로드1
11445정성태1/20/201820799.NET Framework: 728. windbg - 눈으로 확인하는 Workstation GC / Server GC
11444정성태1/19/201820341VS.NET IDE: 125. Visual Studio에서 Selenium WebDriver를 이용한 웹 브라우저 단위 테스트 구성파일 다운로드1
11443정성태1/18/201821794VC++: 124. libuv 모듈 살펴 보기
11442정성태1/18/201818823개발 환경 구성: 353. ASP.NET Core 프로젝트의 "Enable unmanaged code debugging" 옵션 켜는 방법
11441정성태1/18/201817281오류 유형: 447. ASP.NET Core 배포 오류 - Ensure that restore has run and that you have included '...' in the TargetFrameworks for your project.
11440정성태1/17/201820601.NET Framework: 727. ASP.NET의 HttpContext.Current 구현에 대응하는 ASP.NET Core의 IHttpContextAccessor/HttpContextAccessor 사용법파일 다운로드1
11439정성태1/17/201826278기타: 69. C# - CPU 100% 부하 주는 프로그램파일 다운로드1
11438정성태1/17/201820180오류 유형: 446. Error CS0234 The type or namespace name 'ITuple' does not exist in the namespace
... 91  92  93  94  95  96  97  98  99  [100]  101  102  103  104  105  ...