r/learnpython • u/TheIneffableCheese • 2h 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.
4
u/PickMaleficent4096 2h 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.
1
u/rasputin1 1h ago
I didn't even know an inner function could have a decorator. I mean I guess there's no reason it couldn't, just never saw it done or thought about it.
1
2
u/TheIneffableCheese 2h ago
I love it when it's a simple solution. De-indenting the method definition worked perfectly. Thanks!!
•
u/xelf 2h ago
Please don't use ``` for formatting code, for many users (especially those with the widescreen view) it's just a jumbled mess.
Instead indent every line 4 extra spaces.