How to inherit from MonkeyDevice?

孤街醉人 提交于 2019-12-10 12:49:44

问题


I would like to extend the MonkeyDevice class of the monkeyrunner API. My derived class looks like this.

from com.android.monkeyrunner import MonkeyDevice, MonkeyRunner

class TestDevice(MonkeyDevice):
    def __init__(self, serial=None):
        MonkeyDevice.__init__(self)
        self = MonkeyRunner.waitForConnection(deviceId=serial) 
        self.serial = serial

When I call test_dev = TestDevice(serial) from another module I get the following error:

    test_dev = TestDevice(serial)
TypeError: _new_impl(): 1st arg can't be coerced to com.android.monkeyrunner.core.IMonkeyDevice

What am I doing wrong?

Thanks in advance!


回答1:


It appears you cannot directly initialize a MonkeyDevice instance without a call to a factory function waitForConnection. So instead you need to assign self in your __new__() function so that MonkeyDevice recognizes the instance as inheriting from IMonkeyDevice before you call it's __init__

Example:

class TestDevice(MonkeyDevice):
    def __new__(self, serial=None):
        return MonkeyRunner.waitForConnection(deviceId=serial) 
    def __init__(self):
        MonkeyDevice.__init__(self)



回答2:


It seems you are trying to extend a MonkeyDevice instance returned by factory call waitForConnection.

When you try to substitute self inside the construtor you get an error (?). I suspect you are running Jython, as CPython would not complain here, instead a local variable self is created and its value lost.

Anyway to achieve what you want you should create a class with custom __new__ rather than __init__, get your MonkeyDevice instance from the factory and inject your stuff into the instance or it's class/bases/etc.

Alternatively you could wrap MonkeyDevice into another class and pass monkey-ish calls and member access though __getattr__ and __setattr__.



来源:https://stackoverflow.com/questions/7433433/how-to-inherit-from-monkeydevice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!