【发布时间】:2016-08-03 12:25:56
【问题描述】:
我正在为通过 Pythonnet 访问的 C# API 编写 Python 包装类。 由于我想用自己的方法扩展 API,我决定使用here 概述的组合方法来包装它:
C# API 大量使用了我想在我的 Python 代码中模仿的属性。以下最小示例显示了我当前对具有宽度和高度两个属性的 C# Surface 类示例的方法:
class MySurface:
def __init__(api_surface):
self.api_surface = api_surface
@property
def width(self):
return self.api_surface.width
@width.setter
def width(self, value):
self.api_surface.width = value
@property
def height(self):
return self.api_surface.height
@height.setter
def height(self, value):
self.api_surface.height = value
我总共需要处理大约 50 个属性。对于几组属性,我想添加自己的错误检查、类型转换等。 我正在寻找的是一种定义属性的 Pythonic 方式,例如通过工厂或使用描述符。感谢您的帮助!
编辑:我希望能够在 python shell 中使用制表符完成,即表面。 {hit tab} 应该建议surface.width 和surface.height。 Greg 概述的 getattr 方法似乎无法做到这一点。
【问题讨论】:
标签: python properties factory descriptor python.net