Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否可以从operator.methodcaller获取函数名?_Python - Fatal编程技术网

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

Python 是否可以从operator.methodcaller获取函数名?,python,Python,是否可以从Python中的operator.methodcaller获取函数名 import operator as op mc = op.methodcaller('foo') print magic(mc) #should print 'foo' 如何神奇地获得methodcaller调用的方法的名称?的确如此,但您需要深入了解C内部,这不是推荐的解决方案: from ctypes import * PyObject_HEAD = [ ("ob_refcnt", c_size_t

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

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

如何神奇地获得methodcaller调用的方法的名称?

的确如此,但您需要深入了解C内部,这不是推荐的解决方案:

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

请注意,这只适用于CPython,并不特别漂亮。但如果这是唯一可用的解决方案,总比没有好。

是的,但您需要深入研究C内部,而不是推荐的解决方案:

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

请注意,这只适用于CPython,并不特别漂亮。但是,如果这是唯一可用的解决方案,总比没有好。

更新以删除导致Python崩溃的一些错误-现在应该可以开箱即用了。它“神奇地”起作用,我想我必须深入研究C的内部结构才能理解它,非常感谢@nightcracker更新以删除一些导致Python崩溃的bug-它现在应该可以开箱即用了。它“神奇地”工作了,我想我必须深入C的内部来理解它,非常感谢@nightcracker