Microsoft MVP성태의 닷넷 이야기
스크립트: 52. 파이썬 3.x에서의 동적 함수 추가 [링크 복사], [링크+제목 복사],
조회: 3630
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

파이썬 3.x에서의 동적 함수 추가

지난 글에 다룬,

파이썬 2.x에서의 동적 함수 추가
; https://www.sysnet.pe.kr/2/0/13379

코드를 Python 3.x 환경에서 실습해 봅니다. ^^




우선, 전역 함수를 클래스로 가져오는 것은 파이썬 3.x에서도 동일하게 다룰 수 있습니다.

def f_instance(self, arg):
    print('f_instance', self, arg)

def f_static(arg):
    print('f_static', arg)

def f_class(cls, arg):
    print('f_class', cls, arg)

class MyObject:
    def __init__(self):
        pass

MyObject.fi = f_instance
MyObject.fs = staticmethod(f_static)
MyObject.fc = classmethod(f_class)

myobj = MyObject()

myobj.fi('test1') 
myobj.fs('test2') 
myobj.fc('test3') 

print(type(MyObject.fi))
print(type(MyObject.fs))
print(type(MyObject.fc))

/* 출력 결과
f_instance <__main__.MyObject object at 0x7fa443db9970> test1
f_static test2
f_class <class '__main__.MyObject'> test3

<class 'function'>
<class 'function'>
<class 'method'>
*/

또한, 인스턴스 함수의 경우에 대해 types 모듈에 구현된 MethodType을,

# types.py (python 3.8)

# ...[생략]...

class _C:
    def _m(self): pass
MethodType = type(_C()._m)  # 동일한 역할을 했던 UnboundMethodType은 삭제됨

# ...[생략]...

경유해 구현하는 것도 동일한데요, 단지 차이점은 2개의 인자만 받는다는 점과 클래스 함수까지 재정의할 수 있어서 다음과 같은 코드가 가능합니다.

from types import MethodType

def f_instance(self, arg):
    print('f_instance', self, arg)

def f_class(cls, arg):
    print('f_class', cls, arg)

class MyObject:
    def __init__(self):
        pass

myobj = MyObject()
myobj.fi = MethodType(f_instance, myobj)  # 인스턴스 함수인 경우

MyObject.fc = MethodType(f_class, MyObject)  # 클래스 함수인 경우

myobj.fi('test')  # f_instance <__main__.MyObject object at 0x7f3a386fab50> test
myobj.fc('test2')  # f_class <class '__main__.MyObject'> test2

obj2 = MyObject()
obj2.fi('test3')  # (당연히) 예외 발생 AttributeError: 'MyObject' object has no attribute 'fi'
obj2.fc('test4')  # f_class <class '__main__.MyObject'> test4




다른 클래스로부터 가져오는 것도 파이썬 2.x와 비교해 다소 바뀐 점이 있습니다. 2.x에서는 정적 함수만 직관적인 동작을 했는데, 3.x부터는 인스턴스와 정적 함수가 모두 의도한 동작을 하게 됩니다.

class D:
    def __init__(self):
        pass

    def f_instance(self, arg):
        print( 'D.f_instance', self, arg)

    @staticmethod
    def f_static(arg):
        print( 'D.f_static', arg)

    @classmethod
    def f_class(cls_d, cls_my, arg):
        print( 'D.f_class', cls_d, cls_my, arg)


class MyObject:
    def __init__(self):
        pass

MyObject.fi = D.f_instance
MyObject.fs = staticmethod(D.f_static)
MyObject.fc = classmethod(D.f_class)

myobj = MyObject()

myobj.fi('test1')  # D 타입에 정의된 함수지만 self는 myobj 인스턴스가 전달됨
myobj.fs('test2')
myobj.fc('test3')  # 2.x에서와 마찬가지로 class를 받는 인자 2개가 필요


/* 출력 결과
D.f_instance <__main__.MyObject object at 0x7f238dae3970> test1
D.f_static test2
D.f_class   test3
*/

그런데, 과연 D 클래스에 정의된 함수에 MyObject 타입의 인스턴스가 넘어가는 것이 올바른 걸까요? 어찌 보면 이게 더 이상한 동작일 수 있습니다. 그래서 이번에는 오히려 D 인스턴스를 넘겨주기 위해 우회 방법을 사용해야 하는데요,

from functools import partial
from types import MethodType

class D:
    def __init__(self):
        pass

    def fi(self, arg):
        print('D.fi', self, arg)

class MyObject:
    def __init__(self):
        self.proxy = D()

def call_proxy(name, self, *args):
    return getattr(self.proxy, name)(*args)

method_name = 'fi'
p = partial(call_proxy, method_name)
p.__name__ = method_name
p.__doc__ = getattr(D, method_name).__doc__
m = MethodType(p, MyObject)
setattr(MyObject, method_name, m)

myobj = MyObject()

myobj.fi('test1')  # 예외 발생
/*
Traceback (most recent call last):
  File "test.py", line 30, in 
    myobj.fi('test1')
  File "test.py", line 18, in call_proxy
    return getattr(self.proxy, name)(*args)
AttributeError: type object 'MyObject' has no attribute 'proxy'
*/

이번엔 예외가 발생합니다. 이유는, 바뀐 MethodType 타입의 동작 때문입니다. 위에서 MethodType(p, MyObject)로 "클래스 MyObject"를 전달했기 때문에 call_proxy에 넘겨진 self는 MyObject의 인스턴스가 아닌 클래스 자체의 타입입니다.

def call_proxy(name, cls, *args):
    return getattr(cls.proxy, name)(*args)

즉, 클래스 수준에서는 proxy 멤버가 없기 때문에 "AttributeError: type object 'MyObject' has no attribute 'proxy'" 예외가 발생하는 것은 당연한 결과입니다. 따라서 3.x에서는 다른 클래스로부터 가져온 인스턴스 함수는 현실적으로 정상 동작을 할 수 없게 됩니다.




아마도 저런 제약이 문제가 된 것인지, 파이썬 3.x의 socket 모듈은 구현 방식이 바뀌었습니다. 기존에는 _socket 모듈의 socket 타입에 있는 함수를 병합하는 방식이었지만, 3.x에서는 _socket.socket으로부터 상속해 구현하고 있습니다.

class socket(_socket.socket):

    """A subclass of _socket.socket adding the makefile() method."""

    __slots__ = ["__weakref__", "_io_refs", "_closed"]

    def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
        # ...[생략]...

    def dup(self):
        # ...[생략]...

    def accept(self):
        # ...[생략]...

    def makefile(self, mode="r", buffering=None, *,
        # ...[생략]...

    def _sendfile_use_send(self, file, offset=0, count=None):
        # ...[생략]...

    def _check_sendfile_params(self, file, offset, count):
        # ...[생략]...

    def sendfile(self, file, offset=0, count=None):
        # ...[생략]...

    def _decref_socketios(self):
        # ...[생략]...

    def _real_close(self, _ss=_socket.socket):
        # ...[생략]...

    def close(self):
        # ...[생략]...

    def detach(self):
        # ...[생략]...

    @property
    def family(self):
        # ...[생략]...

    @property
    def type(self):
        # ...[생략]...

    # ...[생략]...

덕분에 (2.x에서는 문제가 되었지만) connect 함수 등의 qualname을 구하는 것이 가능합니다.

import socket

print(socket.socket.accept.__qualname__)
print(socket.socket.connect.__qualname__)  # 2.x에서는 qualname을 이용해도 오류

기타 시간되시면 다음의 Q&A 글도 한번 읽어보시고. ^^

Adding a method to an existing object instance in Python
; https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance-in-python





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/24/2023]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13027정성태4/12/20227424.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228947.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20228246.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226723.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20227051.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226992Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20227175Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226950.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226920.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227410.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20227170.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20228140.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229412.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227977VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226218개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225565오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20227152오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225998오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227690개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226989VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226552.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227689.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226516오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226520디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226604.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20227435.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...