首页 > 解决方案 > 试图从父类继承变量“NameError: name 'r' is not defined”

问题描述

我似乎无法从父“Circle”类中获取半径“r”变量并在子“Cylinder”类中使用它。尝试了多种不同的方法,似乎找不到我的错误!

class Circle(Point):

    def __init__(self, r):
        self.r = r

class Cylinder(Circle):

    def __init__(self,h):
        Circle.__init__(self,r)
        self.h = h

此代码导致以下错误

>>> circle = Circle(5)
>>> cylinder = Cylinder(3)
Traceback (most recent call last):
  File "<pyshell#123>", line 1, in <module>
    cylinder = Cylinder(3)
  File "C:/Users/theco/Desktop/OOP Shape.py", line 49, in __init__
    Circle.__init__(self, r)
NameError: name 'r' is not defined

任何帮助,将不胜感激!谢谢!

标签: python-3.x

解决方案


您的代码有一些问题。

  1. 你不是通过doing调用超类的构造函数CircleCircle.__init__(self,r)而是通过doing super().__init__(r),也就是说我要调用superorParent类的构造函数

  2. 您没有传入r, 的构造函数Cylinder(您只是这样做,__init__(self,h):但不知何故您将其传递给Circle不可能的构造函数,您需要同时传递r和传递给likeh的构造函数Cylinder__init__(self, r, h):

所以你的固定代码看起来像

class Circle(Point):

    def __init__(self, r):
        self.r = r

class Cylinder(Circle):

    #Passing both r and h to Cylinder constructor
    def __init__(self,r, h):
        #Passing r to Circle Constructor
        super().__init__(r)
        self.h = h

然后当你相应地调用它时,你会看到它现在可以工作了

circle = Circle(5)
print(circle.r)
#5
cylinder = Cylinder(5, 3)
print(cylinder.r)
#5
print(cylinder.h)
#3

也只是为了幽默自己,尝试分别定义areavolume发挥作用CircleCylinder你会看到继承的力量

import math
class Circle(Point):

    def __init__(self, r):
        self.r = r

    #Area of circle is pi*r*r
    def area(self):

       return math.pi * self.r * self.r

class Cylinder(Circle):

    #Passing both r and h to Cylinder constructor
    def __init__(self,r, h):
        #Passing r to Circle Constructor
        super().__init__(r)
        self.h = h

    #Volume of cylinder is pi*r*r*h
    def volume(self):

        return self.area()*self.h

然后您可以按如下方式调用它们:

circle = Circle(5)
print(circle.area())
#78.53981633974483
cylinder = Cylinder(5, 3)
print(cylinder.volume())
#235.61944901923448

推荐阅读