You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码报错AttributeError:'table'对象不存在'displayTable'属性的问题求助

Fixing the AttributeError: 'table' object has no attribute '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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:29:08