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)
可以直接使用
types.MethodType
构造方法对象:请注意
types.MethodType
的签名可能会更改。在Python2中,当未绑定的方法对象仍然存在时,情况就不同了相关问题 更多 >
编程相关推荐