簡體   English   中英

如何從子 class 訪問父 class 中的顯示方法?

[英]How to access show method in parent class from child class?

class Parent:
    def __init__(self):
        self.__num = 100

    def show(self):
        print("Parent:",self.__num)

class Child(Parent):  
    def __init__(self):
        self.__var = 10
    def show(self):
        super().show()
        print("Child:",self.__var)   

obj1 = Child()
obj1.show()

文件“main.py”,第 12 行,顯示
超級()。顯示()
文件“main.py”,第 6 行,顯示
print("父母:",self.__num)
AttributeError: 'Child' object 沒有屬性 '_Parent__num'

您需要在子 class 中初始化父實例,因為__num屬性僅在Parent初始化期間設置,而不是在Child初始化期間設置。

class Child(Parent):  
    def __init__(self):
        super().__init__()
        self.__var = 10
    def show(self):
        super().show()
        print("Child:",self.__var)   
class Parent:
    def __init__(self):
        self.__num = 100

    def show(self):
        print("Parent:",self.__num)

class Child(Parent):  
    def __init__(self):
        super().__init__()  # Solution
        self.__var = 10

    def show(self):
        super().show()
        print("Child:",self.__var)   

obj1 = Child()
obj1.show()

為避免覆蓋嘗試此操作。

class Parent:
  def __init__(self):
    self.__num = 100

  def show(self):
     print("Parent:",self.__num)

class Child(Parent):  
  def __init__(self):
     Parent.__init__(self)
     self.__var=10
  def show1(self):
    print("Child:",self.__var)   

obj1 = Child()
obj1.show()

改變你的孩子。 初始化為:

def __init__(self):
    self.__var = 10
    super().__init__()

正如其他答案已經說過的那樣,您需要將super().__init__()添加到您孩子 class 的__init__中。

但還要注意,這里有一種叫做名字修飾的東西。 閱讀例如3. Double Leading Underscore: __var on this page

簡短的版本是:如果您想在子 class 中也使用屬性self.__num ,則應將其重命名為self._num (僅一個下划線)。

暫無
暫無

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

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