python-3.x - 试图从父类继承变量“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
任何帮助,将不胜感激!谢谢!
解决方案
您的代码有一些问题。
你不是通过doing调用超类的构造函数
Circle
,Circle.__init__(self,r)
而是通过doingsuper().__init__(r)
,也就是说我要调用super
orParent
类的构造函数您没有传入
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
也只是为了幽默自己,尝试分别定义area
和volume
发挥作用Circle
,Cylinder
你会看到继承的力量
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
推荐阅读
- javascript - 如何在html中使用css将两个div包装在另一个div中
- java - 如何使用 maven 命令运行 Test dependsOnGroups
- wordpress - 从注册页面中删除电子邮件
- java - Lombok 的 @Builder 和 Javadoc 创建
- python - 使用 Snowflake Python 连接器查询 Snowflake 样本数据时出现 UTF-8 解码错误
- java - 将 0 到 255(1 字节)范围的 10 个不同值编码为 3 字节长度值并将其恢复为原始值
- javascript - 如何使用 Wikipedia 的 URL 获取 Wikipedia 内容?
- python - 根据数据框中的值从字典中删除嵌套的键值对
- asp.net-core - ASP.NET Core Web API 操作的永久不记名令牌身份验证
- python - conda环境需要pipwin