Android 继承MonkeyDevice的Python类

Android 继承MonkeyDevice的Python类,android,python,monkeyrunner,Android,Python,Monkeyrunner,我遵循这里给出的解决方案,并添加了一个方法来将功能扩展到我的设备类。 我发现一个错误对象没有属性“test”。看起来我的类实例是MonkeyDevice类型。我做错了什么 from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage class Device(MonkeyDevice): def __new__(self): return MonkeyRunner.waitF

我遵循这里给出的解决方案,并添加了一个方法来将功能扩展到我的设备类。

我发现一个错误对象没有属性“test”。看起来我的类实例是MonkeyDevice类型。我做错了什么

from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage

class Device(MonkeyDevice):

    def __new__(self):
        return MonkeyRunner.waitForConnection(10) 
    def __init__(self):
        MonkeyDevice.__init__(self)
    def test():
        print "this is test"

device = Device()
device.test(self)

你做了很多错事。不幸的是,我没有使用
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
但是,这一点都没有用,因为
设备
可能只是一个函数:

>>> def Device():
...     def test():
...             print "I'm test"
...     inst = MonkeyRunner()
...     inst.test = test
...     return inst
... 
>>> device = Device()
>>> device.test()
I'm test
如果
waitForConnection
是一个
staticmethod
的话,那么至少在
waitForConnection
是一个
staticmethod
的情况下,您不能对
MonkeyRunner
进行子类化并从其
waitForConnection
方法创建实例

我要做的是使用授权:

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"

\uuuu new\uuuu
是用于实际实例化对象的方法。因为您已重写它并显式返回MonkeyRunner.waitForConnection返回的内容,所以该设备实际上不是类device的实例

很少需要重写
\uuuu new\uuuu

编辑 好的,我从链接的答案中看到,在这种情况下,你需要这样做。Bakuriu的回答显示了使用特殊构造函数实例化对象的一些方法,正如
\uuuuuu new\uuuuuu
的文档一样:


作为一个小提示,按照惯例,
\uuuu new\uuuu
的第一个参数是cls而不是self,因为它实际上是类对象本身而不是实例。

非常感谢您的所有回答,尤其是最后一个。
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"