从 getter/setter 到属性的自动转换
我有一个用 C++ 编写的大型库,有人创建了一个接口以自动方式在 python (2.6) 中使用它。现在我有很多带有 getter 和 setter 方法的类。真的:我讨厌他们。
我想使用属性通过更Pythonic 的接口重新实现这些类。问题是每个类都有数百个 getter 和 setter,而我有很多类。如何自动创建属性?
例如,如果我有一个名为 MyClass
的类,其中包含 GetX()
和 SetX(x)
、GetY
, SetY
等...方法,如何自动创建具有属性 X
的派生类 MyPythonicClass
(如果有 getter 则可读如果有设置器,则可写),依此类推?我想要一种机制,让我可以选择跳过一些最好手动完成工作的 getter/setter 对。
I have a big library written in C++ and someone created an interface to use it in python (2.6) in an automatic way. Now I have a lot of classes with getter and setter methods. Really: I hate them.
I want to re-implement the classes with a more pythonic interface using properties. The problem is that every class has hundreds of getters and setters and I have a lot of classes. How can I automatically create properties?
For example, if I have a class called MyClass
with a GetX()
and SetX(x)
, GetY
, SetY
, etc... methods, how can I automatically create a derived class MyPythonicClass
with the property X
(readable if there is the getter and writable if there is the setter), and so on? I would like a mechanism that lets me to choose to skip some getter/setter couples where it is better to do the work by hand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是使用类装饰器的方法
这是一个稍微复杂的版本,允许您指定要跳过的项目列表
Here's a way to do it with a class decorator
Here is a slightly more complicated version that allows you to specify a list of items to skip
使用 元类 查找所有属性,例如
Get*
和Set*
并向类添加适当的属性。拥有一个类属性,您可以将其设置为包含将跳过的属性的序列。有关详细信息,请参阅此答案在类中设置属性。Use a metaclass that looks for all attributes like
Get*
andSet*
and adds appropriate properties to the class. Have a class attribute that you can set to a sequence containing properties that will be skipped. See this answer for details about setting attributes in the class.使用魔法时要小心,尤其是用魔法改变他人的束缚。这样做的缺点是
考虑一下,直接处理您正在使用的库是否更有意义。
Be careful using magic, especially magically altering other people's bindings. This has the disadvantages that
Consider whether it wouldn't make more sense just to deal with the library you are using as it came to you.