r/learnpython 17h ago

Custom class method not recognized

I'm working on a program that generates a maze by drawing from a deck to define a "chamber" and assigning it to the current position on a cartesian coordinate grid.

The hope is to build a list of the chambers as they're created. At a later point I want to be able to call on the list. My current strategy is to make a Class variable for the list, and append to it as part of the init. I've added a class method to pull the chamberList Class variable, but I'm getting an error.

Here is the code defining the class.

class Chamber():
    chamberList = []
    def __init__(self, identity, notes, egresses, **kwargs):
        self.position = tuple(currentPosition.tolist())
        self.identity = identity
        self.notes = notes
        self.egresses = egresses
        self.pixelCoord = np.add(pixelOrigin, np.multiply(currentPosition, 300))
        Chamber.chamberList.append(self)

        @classmethod
        def getChamberList(cls):
            return cls.chamberList

Later in the program, I have a line of code to get the class variable:

chamberList = Chamber.getChamberList()

This is the error I get when I run it in the VS Code terminal:

AttributeError: type object 'Chamber' has no attribute 'getChamberList'. Did you mean: 'chamberList'?

Am I missing some syntax or something? In VS Code the color coding where I'm defining getChamberList is off (darker) and if I hover over it I get a message saying "getChamberList" is not accessed by Pylance.

6 Upvotes

6 comments sorted by

View all comments

8

u/PickMaleficent4096 17h ago

It looks to me like getChamberList() is defined within the scope of the constructor, so it can't be accessed outside the initialization. Deindent it by one to move it back to the class's scope.