簡體   English   中英

我的子類無法從 Python 中的父類正確繼承

[英]My subclass can't heritate properly from parent class in Python

我有一個名為 "Product" 的類,它繼承自名為 "Command" 的基類。 每次我通過調用基類“L_R”中的屬性來執行如下所示的 function1 時,它會顯示“NameError:name 'L_R' is not defined”

class Command:
   def__init__(self ,L_R,L_A,L_M):
    self.L_R=L_R
    self.L_M=L_M
    self.L_A=L_A
    ######
class Produit(Command): 
     def __init__(self, reference,position):
        super().__init__(self,L_R,L_A,L_M)
        self.reference=reference
        self.position=position

     def function1(self)
        ###
        if (self.L_R==condition):
            #some code

我認為 super() 有問題,但我找不到

是的,根據您上面的代碼,您的 super 有點不正確。 我不會試圖解釋你的class ,只是告訴你如何修復你的 super 來繼承你的 L_R, L_A, L_M 參數。 如果您希望 Produit 在每次實例化時專門繼承它們,您需要將它們傳遞給super()__init__

class Command:
   def__init__(self ,L_R,L_A,L_M):
    self.L_R=L_R
    self.L_M=L_M
    self.L_A=L_A
    ######
class Produit(Command): 
     def __init__(self, L_R, L_A, L_M, reference, position):
        super().__init__(L_R,L_A,L_M)
        self.reference=reference
        self.position=position

     def function1(self)
        ###
        if (self.L_R==condition):
            #some code

如果您希望Produit繼承您從 command 創建的任何內容,您可以執行以下操作:

my_cmd_obj = Command(L_R, L_A, L_M)
my_prd_obj = Produit(my_cmd_obj, reference, position)

其中L_R, L_A, L_M, reference, position是實際程序中的變量,應該是類的參數。

暫無
暫無

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

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