簡體   English   中英

如何訪問子類中的父類方法

[英]How to access Parent class methods in subclass

類“ X”是父類,類“ Y”是X的子類。類Y的子類如何訪問作為其父類的類X。

class x:
    def __init__(self,text):
      self.text = t

    def printThis(self):
        text = self.text
        print(text)

class y(x):

    def test():
        printThis(text)

a = y("printing")

a.printThis()

Y類的子類如何訪問其父類的類X。

Python具有多重繼承,因此一個類可能擁有多個父類。 所有這些都由“ mro”(方法順序解析)和super()對象處理 ,您可以從mro中的“ next”類訪問方法。

現在請注意,在代碼段中,真正的問題根本不是“訪問父類”,而是您正在嘗試訪問全局 “ printThis”名稱-未定義。 Python沒有像Java這樣的“隱式表示”,您必須使用self來引用實例屬性或方法,因此您需要的是:

class Y(X):
    def test(self):
        self.printThis()

為了說明這一點與父類無關,在同一個類中沒有self的情況下調用printThis()相同的問題:

class Example():
    def __init__(self, text):
        self.text = text

    def printThis(self):
        print(self.text)

    def test(self):
       # this will fail just as well
       printThis()

另外,這里不需要super() ,Python會在定義此名稱的mro的第一個類上解析printThis 當您的子類重新定義父類的方法並且仍想調用父類的實現時,您需要super() ,即:

class Example():
    def __init__(self, text):
        self.text = text

    def printThis(self):
        print(self.text)


class Child(Example):
    def printThis(self):
        print("this is a test")
        super().printThis()
        print("test passed")

在y類的init中,您還必須初始化要從其繼承的父類。

class x:
    def __init__(self, text):
        self.text = text

class y(x):
    def __init__ (self, #other vars here ):
        x.__init__(self, text)
        self.othervars = othervars

    def test():
        self.printThis(self.text)

暫無
暫無

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

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