你正在做的很多事情是错误的。不幸的是,我不使用monkeyrunner
,所以我无法帮助您了解与库本身相关的细节。
你的代码做什么是类似如下:
>>> class MonkeyRunner(object): pass
...
>>> class Device(MonkeyRunner):
... def __new__(self):
... return MonkeyRunner()
... def __init__(self):
... super(Device, self).__init__()
... def test():
... print "This is test"
...
>>> device = Device()
>>> device.test(self)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MonkeyRunner' object has no attribute 'test'
>>> device
<__main__.MonkeyRunner object at 0xb743fb0c>
>>> isinstance(device, Device)
False
注意如何device
是不一个Device
实例。原因是您的__new__
方法未返回Device
实例,而是一个MonkeyRunner
实例。你在你的问题链接的答案说:
反正达到你想要,你应该创建一个自定义的类 __new__
而非__init__
,从工厂让您MonkeyDevice
实例 和注入你的东西到什么实例或它的 class/bases /等。
这意味着你应该做的是这样的:
>>> class Device(MonkeyRunner):
... def __new__(self):
... inst = MonkeyRunner()
... inst.test = Device.test
... return inst
... @staticmethod
... def test():
... print "I'm test"
...
>>> device = Device()
>>> device.test()
I'm test
然而,这是没有作用的,因为Device
可能仅仅是一个功能:
>>> def Device():
... def test():
... print "I'm test"
... inst = MonkeyRunner()
... inst.test = test
... return inst
...
>>> device = Device()
>>> device.test()
I'm test
AFAIK你不能子类MonkeyRunner
并从其waitForConnection
方法创建实例,至少如果waitForConnection
是staticmethod
。
我会做的是使用委托:
class Device(object):
def __init__(self):
self._device = MonkeyRunner.waitForConnection(10)
def __getattr__(self, attr):
return getattr(self._device, attr)
def test(self):
print "I'm test"
非常感谢你的回答,尤其是最后一个答案。 – user2344495 2013-05-02 21:33:46