簡體   English   中英

如何從具有基類對象繼承的類調用方法?

[英]How to call a method from a class with inheritence on an object of the base class?

我有兩節課。 一個繼承另一個:

class A(object):
    def __init__(self):
        self.attribute = 1

class B(A):
    def get_attribute(self):
        return self.attribute

我希望能夠從 B 對 A 類型的對象調用方法。我無法編輯 A 類(它是一個內置類)。 當我嘗試從 B 調用方法時,出現 AttributeError。

a = A()
a.get_attribute()

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a.get_attribute()
AttributeError: 'A' object has no attribute 'get_attribute'

有沒有辦法在不顯式聲明數據為 B 類型的情況下從 B 調用方法?

雖然不鼓勵這樣做,但您可以使用任何方法,例如函數。 在你的情況下,這將是

B.get_attribute(a)

原因的方法具有可與類型兼容a

暫無
暫無

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

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