簡體   English   中英

在基礎 class 中使用派生的 class 的屬性

[英]Using attributes from the derived class in the base class

在我正在處理的項目中,我們有一個類層次結構,每個 class 定義一個get_text()方法。

class Base:
    def get_text(self):
        raise NotImplementedError

class Derived1(Base):
    def get_text(self):
        return "Text from Derived1"

class Derived2(Base):
    def get_text(self):
        return "Text from Derived2"

obj1 = Derived1()
print(obj1.get_text())
==> 'Text from Derived1'

obj2 = Derived2()
print(obj2.get_text())
==> 'Text from Derived2'

這樣,程序員可以調用obj.get_text()並從obj指向的 class 中獲取文本。

現在我想將該方法重構為一個屬性(稱為TEXT )。 不過,我想保留原始方法以實現向后兼容性。 有沒有辦法只在基礎 class 中做到這一點?

class Base:
    def get_text(self):
        """
        Keep backward compatibility.
        """
        return TEXT  # What should be here?

class Derived1(Base):
    TEXT = "Text from Derived1"

class Derived2(Base):
    TEXT = "Text from Derived2"

obj1 = Derived1()
print(obj1.TEXT)

# Non-refactored code
obj2 = Derived2()
print(obj2.get_text())
==> NameError: name 'TEXT' is not defined

來自 C++,我習慣於使用指向基礎 class 的指針調用派生的 class 使用 ZF6F87C9FDCF8871C2F3 虛擬方法調度的方法。 Python 中是否有類似的可能?

要回答我自己的問題(感謝評論者:)以下兩種方式都有效:

return self.__class__.TEXT

這里, self.__class__指向Derived1Derived2 class 對象,它們可以訪問TEXT

return self.TEXT

使這一步驟更短,因為屬性解析算法會自動訪問 class 屬性。

暫無
暫無

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

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