0

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.

I have initiated the attribute within the class object within 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

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
KButler
  • 97
  • 1
  • 9

1 Answers1

4

I believe this is because you are only using a single underscore (_) around the init, instead of the required double underscore. As such the name mangling will not work properly, meaning the initialisation of the height property will not take place.

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

  • haha. Yes. While i was waiting to see if there would be a response, I noticed that as well> It needed 2 underscores. Thank you. – KButler Apr 16 '19 at 16:01