你正在做的很多事情是錯誤的。不幸的是,我不使用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