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
的内置“实例方法”描述符。可以定义一个,例如,
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)
答案 0 :(得分:1)
您可以直接使用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
的签名可能会更改。在未绑定的方法对象仍然存在的情况下,它在Python 2中与以前不同。