【问题标题】:Inheritance from parent class return attribute error从父类继承返回属性错误
【发布时间】:2022-01-03 07:36:06
【问题描述】:

您好,我尝试从一个类继承一些代码:

class MathParent:
    def multiply(self, number1, number2):
        self.answer = number1 * number2
        return self.answer
    def happy(self):
        return "Nice Mark!"

class MathChild(MathParent):
    def plus_x(self, x) :
        return self.answer + x

p_out = MathParent()
print(p_out.multiply(5, 2))
print(p_out.happy())

c_out = MathChild()
print(c_out.happy())
print(c_out.plus_x(5))

快乐的方法已经成功继承,但是当我访问 self.answer 属性时,它会引发错误。我用另一种方式:

return MathParent.self.answer + x

这仍然不起作用。任何见解都会非常有帮助:)

【问题讨论】:

  • 您希望添加 5 的答案是什么?来自p_out 的那个? p_out 是具有不同实例属性的不同对象。
  • p_out(5, 2) ?它将是 10,因为 5 * 2

标签: python python-3.x class


【解决方案1】:

self.answer 仅在调用 multiply 时才被声明。您可以将构造函数添加为harshraj22 状态,但在现有代码中,您需要在调用plus_x 之前调用multiply

这个:

c_out = MathChild()
print(c_out.happy())
c_out.multiply(1, 1)
print(c_out.plus_x(5))

运行没有错误。

【讨论】:

  • 嗯,但是当我运行时,答案变为 6,因为 1 * 1 = 1 然后 1 + 5 = 6。我期望 15 因为 5 * 2 = 10 然后 10 + 5 = 15
  • p_outc_out 指的是两个独立的对象。如果你想使用来自p_out 的结果,请将其实例化为MathChild 的实例,然后在其上调用.multiply(5, 2).plus_x(5)
  • 啊我明白了.. 非常感谢
【解决方案2】:

self.answer 变量仅在multiply 函数运行时创建。 解决此问题的一种方法是,您可以使用以下方法确保在调用 __init__ 后创建变量:


class MathParent:
    def __init__(self) -> None:
        self.answer = 0

    def multiply(self, number1, number2):
        self.answer = number1 * number2
        return self.answer
    def happy(self):
        return "Nice Mark!"

class MathChild(MathParent):
    def plus_x(self, x) :
        return self.answer + x

p_out = MathParent()
print(p_out.multiply(5, 2))
print(p_out.happy())

c_out = MathChild()
print(c_out.happy())
print(c_out.plus_x(5))

【讨论】:

  • 嗯,但是当我运行时,答案变成了 5?我期望 15 因为 5 * 2 = 10 然后 10 + 5 = 15
  • @JLz18191 p_outc_out 是两个不同的对象。 multiply() 是在 p_out 上完成的。 print(c_out.multiply(5, 2))c_out.plus_x(... ) 之前添加它以获得预期的输出。做print(p_out.answer)print(c_out.answer) 以更好地理解
  • 非常感谢。我认为 'init' 不是很有用 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
相关资源
最近更新 更多