[英]Python class to inherit MonkeyDevice
我按照这里给出的解决方案,添加了一个方法来将功能扩展到我的Device类。 如何从MonkeyDevice继承?
我得到一个错误对象没有属性'test'。 看起来我的Class实例是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
请注意device
不是 Device
实例。 原因是你的__new__
方法没有返回一个Device
实例,而是一个MonkeyRunner
实例。 您在问题中链接的答案说明:
无论如何要实现你想要的你应该创建一个自定义
__new__
而不是__init__
,从工厂获取你的MonkeyDevice
实例并将你的东西注入实例或它的class / bases /MonkeyDevice
这意味着你应该做的事情如下:
>>> 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
子类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"
__new__
是用于实际实例化对象的方法。 因为你已经重写它并显式返回了MonkeyRunner.waitForConnection返回的内容,所以device实际上并不是类Device的实例。
很少需要覆盖__new__
。
编辑好了,我从链接的答案中看到,这是你需要这样做的情况。 Bakuriu的答案显示了一些使用特殊构造函数来实例化对象的方法, __new__
的文档也是__new__
: Python文档
作为次要注释,按照惯例, __new__
的第一个参数是cls而不是self,因为它实际上是类对象本身而不是实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.