Python:向类添加默认函数??或类运算符不确定



我还在学习很多东西。所以请放轻松。:)

我有2节课,每个人和那里的兄弟在工作中使用。 我有一些功能想要添加。

第 1 类: foo_the_unchangeable(具有python包装器的c代码,是我们产品的接口库(

第 2 类:
foo_used_by_all

m=foo_the_unchangeable()

因此,当我为我们的产品编写测试脚本时,我确实会这样想

MyObj = foo_used_by_all()
x = MyObj.m.Item("some text showing product options").Value
z = MyObj.m.Item("some text showing product options").DisplayValue

MyObj.m.Item("some text showing product options").Value = 9<br>
MyObj.m.Item("some text showing product options").DisplayValue = "Mark"

我想写的代码是:

MyObj = ()
x = MyObj("some text showing product options").Value
Y = MyObj("some text showing product options").DisplayValue

MyObj("some text showing product options").Value = 9
MyObj("some text showing product options").DisplayValue = "Mark"

我不确定该怎么上课foo_used_by_all这样我就可以按照我想要的方式编写脚本。 我能够创建一个返回类的成员函数。它很接近;但不完全是我想要的。

foo_used_by_all
def Item(self, text_str)
return self.m.Item(text_str)

如果有人能指出我正确的方向,那将是有帮助的。

看起来你想实现__call__()方法:

class UsedByAll:
def __init__(self):
self.api = TheUnchangeable()
def __call__(self, text):
return self.api.Item(text)

鉴于显示的名称,请查看PEP8。

怎么样

MyObj = foo_used_by_all()
MyItem = MyObj.m.Item    # or MyObj = MyObj.m.Item

然后

x = MyItem("some text showing product options").Value
Y = MyItem("some text showing product options").DisplayValue
MyItem("some text showing product options").Value = 9
MyItem("some text showing product options").DisplayValue = "Mark"

相关内容

最新更新