簡體   English   中英

當 Parent 已經明確地“setattr”相同的 function 時,如何覆蓋 function?

[英]How to override a function when Parent already explicitly `setattr` the same function?

我創建的“最小”示例:

class C:
    def wave(self):
        print("C waves")

class A:
    def __init__(self):
        c = C()
        setattr(self, 'wave', getattr(c, 'wave'))

class B(A):
    def wave(self):
        print("B waves")

>>> a = A()
>>> a.wave()
C waves # as expected
>>> b = B()
>>> b.wave()
C waves # why not 'B waves'?
>>> 

In the example, class A explicitly defined its method wave to be class C 's wave method, although not through the more common function definition, but using setattr instead. 然后我們有繼承A class BB嘗試用自己的方法覆蓋wave方法,但是,這是不可能的,這是怎么回事? 我該如何解決?

如果可能的話,我想保留 class Asetattr樣式定義,請告知。

我從來沒有系統地學習過 Python 所以我想我對 Python 的 inheritance 和setattr的工作方式有一些了解。

Class A 在__init__()中將wave()方法設置為其實例屬性。 這可以通過檢查實例的字典來看到:

>>> b.__dict__
{'wave': <bound method C.wave of <__main__.C object at 0x7ff0b32c63c8>>}

您可以通過從b中刪除實例成員來解決此問題

>>> del b.__dict__['wave']
>>> b.wave()
B waves

刪除實例屬性后, wave() function 然后從 class 字典中獲取:

>>> B.__dict__
mappingproxy({'__module__': '__main__',
              'wave': <function __main__.B.wave(self)>,
              '__doc__': None})

這里要注意的是,當 Python 查找屬性時,實例屬性優先於 class 屬性(除非 class 屬性是數據描述符,但這里不是)。

那時我還寫了一篇博文,更詳細地解釋了屬性查找的工作原理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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