首页 > 解决方案 > 我的子类无法从 Python 中的父类正确继承

问题描述

我有一个名为 "Product" 的类,它继承自名为 "Command" 的基类。每次我通过调用基类“L_R”中的属性来执行如下所示的函数1时,它都会显示“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() 有问题,但我找不到

标签: pythonclassinheritance

解决方案


是的,根据您上面的代码,您的 super 有点不正确。我不会试图解释你的class,只是告诉你如何修复你的 super 以继承你的 L_R、L_A、L_M 参数。如果您希望 Produit 每次实例化时都专门继承它们,您需要将它们传递__init__super():

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继承您从命令创建的任何内容,您可以执行以下操作:

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实际程序中应该作为类参数的变量在哪里。


推荐阅读