J01
J01

Reputation: 145

AttributeError for classes

I'm getting an AttributeError: 'table' object has no attribute 'displayTable' for my code and i'm not sure whats going on

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()

Upvotes: 0

Views: 37

Answers (2)

Adam Oellermann
Adam Oellermann

Reputation: 303

Your displayTable() definition doesn't belong to class table, because it isn't indented under the class. Try it like this:

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() 

Both init and displayTable now belong to class, and they have the same level of indentation.

Upvotes: 1

Jiří Baum
Jiří Baum

Reputation: 6930

You need to indent the displayTable method the same as the __init__ method.

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()

Upvotes: 2

Related Questions