python - 我的子类无法从 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() 有问题,但我找不到
解决方案
是的,根据您上面的代码,您的 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
实际程序中应该作为类参数的变量在哪里。
推荐阅读
- javascript - JS中具有多个级别的嵌套对象的分组数组
- sql - 查询以获取给定父 ID 的子记录
- javascript - 如何使用文件获取表单并在网络核心上接收它?
- python - Django {% extend static "template.html" %} 抛出 TemplateSyntaxError
- javascript - 如何测试检查窗口的脚本是否用开玩笑未定义?
- selenium - WebDriverException:未知错误:DevToolsActivePort 文件不存在
- java - 尝试使用 JLayeredPane 拖动某些东西
- python-3.x - 加快只读字典的python加载时间?
- java - 如何通过意图传递parcelable类而不出现空错误
- javascript - Javascript时钟不起作用