[英]Attribute error while using Object-Oriented Programming in Python
I am getting an attribute error when running the main function. 运行主函数时出现属性错误。 I am calling a class from a separate file.
我正在从单独的文件中调用类。 The error is stating that there is no attribute 'height' in object Drone.
该错误表明对象Drone中没有属性“ height”。
I have initiated the attribute within the class object within drone.py. 我已经在drone.py中的类对象内启动了属性。 I then call it with from drone import Drone.
然后,我将其与从无人机导入的无人机一起调用。 I am not seeing where in lies my issue.
我看不出我的问题在哪里。 I have been playing with it for hours now.
我已经玩了几个小时了。
# drone.py
class Drone:
def _init_(self):
self.height = 0.0
self.speed = 0.0
def accelerate(self):
self.speed = self.speed +10
def decelerate(self):
if self.speed >= 10:
self.speed = self.speed -10
def ascend(self):
self.height = self.height +10
def descend(self):
if self.height >= 10:
self.height = self.height -10
# fly_drone.py
from drone import Drone
def main():
drone1 = Drone()
operation = int(input("Enter 1 for accelerate, 2 for decelerate, 3 for ascend, 4 for descend, 0 for exit:"))
while operation != 0:
if operation == 1:
drone1 = drone1.height
drone1.ascend()
print("Speed:", drone1.speed, "Height:", drone1.height)
main()
I am trying to achieve: Speed: 0 Height: 10 我正在尝试实现:速度:0高度:10
This is my error message: 这是我的错误信息:
Enter 1 for accelerate, 2 for decelerate, 3 for ascend, 4 for descend, 0 for exit:1
Traceback (most recent call last):
File "C:/Python Projects/CSC121Lab13/fly_drone.py", line 12, in <module>
main()
File "C:/Python Projects/CSC121Lab13/fly_drone.py", line 8, in main
drone1 = drone1.height
AttributeError: 'Drone' object has no attribute 'height'
Process finished with exit code 1
I believe this is because you are only using a single underscore (_) around the init, instead of the required double underscore. 我相信这是因为您仅在init周围使用单个下划线(_),而不是必需的双下划线。 As such the name mangling will not work properly, meaning the initialisation of the height property will not take place.
因此,名称重整将无法正常工作,这意味着将不会对height属性进行初始化。
The solution therefore is as follows:- 因此,解决方案如下:
class Drone:
def __init__(self):
self.height = 0.0
self.speed = 0.0
See here for more details on underscores https://stackoverflow.com/a/1301369/11329170 请参阅此处以获取有关下划线的更多详细信息https://stackoverflow.com/a/1301369/11329170
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.