Python代码报错AttributeError:'table'对象不存在'displayTable'属性的问题求助
Hey there! Let's break down what's going wrong here. The error you're seeing almost always boils down to incorrect indentation in your class definition—your displayTable method isn't actually part of the table class right now.
The Root Cause
In Python, class methods need to be indented to the same level as the __init__ method (typically 4 spaces) to be recognized as part of the class. If your displayTable function is left-aligned or indented differently, Python treats it as a standalone function outside the class, so your table instance has no idea it exists.
Corrected Code
Here's your code with the proper indentation fixed:
import random class table: def __init__(self, width, length): self.width = width self.length = length self.frontSide = [["?" for j in range(self.width)] for i in range(self.length)] self.rearSide = [[" " for j in range(self.width)] for i in range(self.length)] def displayTable(self): # prints column numbers print(" 1 2 3") j = 1 for i in self.frontSide: print(j,i) j += 1 print("") a = table(3,2) a.displayTable()
What This Fixes
By indenting the displayTable method to match the __init__ method, you're telling Python that this function belongs to the table class. Now when you create an instance a and call a.displayTable(), Python can find the method and execute it correctly.
Expected Output
When you run the corrected code, you'll see:
1 2 3 1 ['?', '?', '?'] 2 ['?', '?', '?']
内容的提问来源于stack exchange,提问作者J01

