2

是否可以从 Python 中的 operator.methodcaller 获取函数名称?

import operator as op
mc = op.methodcaller('foo')
print magic(mc) #should print 'foo'

如何magic获取方法调用者正在调用的方法的名称?

4

1 回答 1

4

It is, but you need to dig into the C internals (not a recommended solution):

from ctypes import *

PyObject_HEAD = [
    ("ob_refcnt", c_size_t),
    ("ob_type", c_void_p),
]

class methodcallerobject(Structure):
    _fields_ = PyObject_HEAD + [
        ("name", c_void_p),
        ("args", c_void_p),
        ("kwds", c_void_p),
    ]

def magic(methcallobj):
    if not isinstance(methcallobj, operator.methodcaller):
        raise TypeError("not a methodcaller")

    c_methcallobj = cast(c_void_p(id(methcallobj)), POINTER(methodcallerobject)).contents

    return cast(c_methcallobj.name, py_object).value

Note that this only works on CPython and is not particularly beautiful. But if this is the only solution available, it's better than nothing.

于 2012-08-27T11:48:15.297 回答