加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何为所有ctype结构类设置__str__方法?

发布时间:2020-12-20 13:21:48 所属栏目:Python 来源:网络整理
导读:[自问这个问题后,我发现: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/给出了一个很好的答案.] 我刚刚为ctype生成的Structure类’foo’写了一个__str__方法,因此: def foo_to_str(self): s = [] for i in foo._fields_: s.append('{}: {}'.f
[自问这个问题后,我发现: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/给出了一个很好的答案.]

我刚刚为ctype生成的Structure类’foo’写了一个__str__方法,因此:

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

但这是为任何Structure类生成__str__方法的一种相当自然的方法.如何将此方法直接添加到Structure类中,以便ctypes生成的所有Structure类都可以获取它?

(我使用h2xml和xml2py脚本自动生成ctypes代码,这没有提供更改类输出名称的明显方法,因此只需子类化Structure,Union& c.并添加我的__str__方法就会涉及post – 处理xml2py的输出.)

解决方法

不幸的是没有这样的方法.试图修改Structure类本身会导致

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读