获取绑定内置函数的本机方法实例

2024-04-20 09:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

Python数据模型的partially documented行为是__getattribute__不绑定“内置”函数:

import logging, numpy
class TestBind:
    nobind = print
    nobind2 = numpy.array
    binds = logging.error
    def binds2(self): pass

print(TestBind.nobind)
print(TestBind.nobind2)
print(TestBind.binds)
print(TestBind.binds2)
# <built-in function print>
# <built-in function array>
# <function error at 0x1feedbeed>
# <function TestBind.binds2 at 0x1feedbeef>

t = TestBind()

print(t.nobind)
print(t.nobind2)
print(t.binds)
print(t.binds2)
# <built-in function print>
# <built-in function array>
# <bound method error of <__main__.TestBind object at 0x1beefcafe>>
# <bound method TestBind.binds2 of <__main__.TestBind object at 0x1beefcafe>>

print(type(t.binds))
# method

没有与classmethod/staticmethod等效的内置“instancemethod”描述符。一个可以定义,例如

from functools import partial
class instancemethod: 
    __slots__ = '_func',
    def __init__(self, func): 
        self._func = func 
    def __get__(self, inst, cls): 
        return self._func if inst is None else partial(self._func, inst)

class TestBind:
    ibinds = instancemethod(logging.error)
    ...

但结果自然不是method对象,并且缺少绑定方法的属性:

print(t.ibinds)
# functools.partial(<function error at 0x1feedbeed>, <__main__.TestBind object at 0x1051af310>)
t.ibinds.__self__  # AttributeError
t.ibinds.__name__  # AttributeError
t.ibinds.__func__  # AttributeError
t.ibinds.__doc__  # wrong doc

是否可以编写一些instancemethod描述符(或其他任何东西),为C定义的函数生成绑定的method实例

分辨率:

根据莫妮卡下面的回答,我用了

from types import MethodType

class instancemethod:
    """
    Convert a function to be an instance method.
    """
    __slots__ = '_func',
    def __init__(self, func):
        self._func = func
    def __get__(self, inst, owner=None):
        return self._func if inst is None else MethodType(self._func, inst)


1条回答
网友
1楼 · 发布于 2024-04-20 09:22:16

可以直接使用types.MethodType构造方法对象:

import types

class instancemethod:
    def __init__(self, func):
        self.func = func
    def __get__(self, instance, owner=None):
        if instance is None:
            return self.func
        return types.MethodType(self.func, instance)

请注意types.MethodType的签名可能会更改。在Python2中,当未绑定的方法对象仍然存在时,情况就不同了

相关问题 更多 >