Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Attribute Error when running the given python code

How can I effectively debug a Python script that’s raising an ‘AttributeError’ on a seemingly valid object attribute access? I’ve checked the object’s class definition and verified that the attribute exists, but I’m still encountering this error. What are some strategies or tools I can use to track down the root cause of this issue?

class MyClass:
    def __init__(self):
        self.data = []

    def add_item(self, item):
        self.data.append(item)

def main():
    obj = MyClass()
    obj.add_item("apple")
    obj.add_item("banana")

    for item in obj.items:
        print(item)

if __name__ == "__main__":
    main()

I tried to debug my code using the PyCharm Debugger but nothing seemed to work! I am really stuck with this problem pls help

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

class MyClass:
    def __init__(self):
        self.data = []

    def add_item(self, item):
        self.data.append(item)

def main():
    obj = MyClass()
    obj.add_item("apple")
    obj.add_item("banana")

    # Change 'obj.items' to 'obj.data'
    for item in obj.data:
        print(item)

if __name__ == "__main__":
    main()

Replace obj.items with obj.data in the loop to access the correct attribute and fix the AttributeError.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading