Python 如何为所有ctype结构类设置一个_str___方法?

Python 如何为所有ctype结构类设置一个_str___方法?,python,ctypes,Python,Ctypes,[问了这个问题后,我发现:这是一个很好的答案。] 我刚刚为ctype生成的结构类“foo”编写了一个\uuuu str\uuu方法,因此: def foo_to_str(self): s = [] for i in foo._fields_: s.append('{}: {}'.format(i[0], foo.__getattribute__(self, i[0]))) return '\n'.join(s) foo.__str__ = foo_to_str 但这是为任

[问了这个问题后,我发现:这是一个很好的答案。]

我刚刚为ctype生成的结构类“foo”编写了一个
\uuuu str\uuu
方法,因此:

def foo_to_str(self):
  s = []
  for i in foo._fields_:
    s.append('{}: {}'.format(i[0], foo.__getattribute__(self, i[0])))
  return '\n'.join(s)

foo.__str__ = foo_to_str
但这是为任何结构类生成
\uuu str\uu
方法的一种相当自然的方法。如何将此方法直接添加到Structure类中,以便由ctypes生成的所有结构类都能得到它


(我正在使用h2xml和xml2py脚本自动生成ctypes代码,这并没有提供明显的方法来更改输出类的名称,所以简单地将结构、Union&c子类化,并在其中添加我的
\u str\u
方法需要对xml2py的输出进行后处理。)

不幸的是,没有这样的方法。试图修改
结构
类本身会导致

TypeError: can't set attributes of built-in/extension type '_ctypes.Structure'
您可以得到的最接近的是一个包装类,您可以将自己应用到您关心的每个返回结构,其中哪些将非重写方法委托给包装结构。大概是这样的:

class StructureWrapper(object):
    def __init__(self, structure):
        self._ctypes_structure = structure
    def __getattr__(self, name):
        return getattr(self._ctypes_structure, name)
    def __str__(self):
        # interesting code here

一个邪恶的黑客会在与
xml2py
输出相同的目录中创建一个名为
ctypes.py
的文件,从那里导入真正的
ctypes
模块中的所有内容,并用您自己的版本覆盖
结构。但不要引用我的话…什么是福?一个实例还是一个类?是的,这很棘手<代码>类型错误:无法设置内置/扩展类型“\u ctypes.Structure”的属性。
把我搞砸了。我可以用常规的python类来实现,但是我对ctype的知识还不够。也许可以用装饰器或元类做些什么?jon_darkstar,foo是一个类。