gpt4 book ai didi

python - Python C 扩展中的动态方法切换

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:04 25 4
gpt4 key购买 nike

我想创建一个 Python C 扩展模块,其中包含一个类,该类可以根据 __init__() 方法参数值动态别名/更改/选择其方法。我无法在“扩展和嵌入 Python 解释器”文档中找到解决方案。为了说明,这是一个工作的 Python 示例,我想创建等效的 Python C 扩展类:

class Test:
def __init__(self, var):
if var == 'x':
self.func = self.func_x
else:
self.func = self.func_y

def func_x(self):
print('func_x')

def func_y(self):
print('func_y')

list = [Test('x'), Test('y'), Test('z')]
for i in range(len(list)):
list[i].func()

我想编写与 Test 类等效的 C 代码,但创建 list 对象,使用 Python C 扩展 Test 元素别名 func() 方法,在 Python 中。

作为示例实现,以 https://docs.python.org/2/extending/newtypes.html#adding-data-and-methods-to-the-basic-examplenoddy2 模块的 Noddy 类的 Python 文档示例为例,如何扩展此示例 Python C 扩展代码以允许在 Noddy_init() 函数中切换此动态方法?可以复制和修改 Noddy_name() 函数,然后修改 Noddy_init() 以将 self.func 设置为一个或另一个基于第一个 参数值。您会将 self.func() 定义为 PyMemberDef 还是 PyObject?它应该通过 tp_methods 还是 tp_membersPyTypeObject 中注册?在定义了 self.func() 之后,如何才能将所需的 C 函数动态别名为它?

干杯!

最佳答案

您可以通过常规 PyMethodDef 在 C 中实现方法 func 并从 调用 func_afunc_b >func 取决于存储在构造函数中的标志。

关于python - Python C 扩展中的动态方法切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27216575/

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