gpt4 book ai didi

python - 是否可以从 operator.methodcaller 获取函数名称?

转载 作者:行者123 更新时间:2023-11-28 23:00:23 26 4
gpt4 key购买 nike

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

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

我如何使用魔法获取方法调用者正在调用的方法的名称?

最佳答案

是的,但您需要深入了解 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 - 是否可以从 operator.methodcaller 获取函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12141201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com