簡體   English   中英

Python類繼承MonkeyDevice

[英]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方法創建實例,至少如果waitForConnectionstaticmethod

我要做的是使用委托:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM