Advertisements
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
>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
.