I have a class with a few class attributes, that I would like to initialize by using class methods. This is because I have close to 300 items in a list, and I'd rather not have them in the class definition. Since I will be having at minimum, upwards of a few hundred objects of this class, It wouldn't be efficient to read and then create a attribute for each individual instantiation when they won't be modifiying the two lists I've defined, and only reading from them.
class exampleClass:
@classmethod
def getUnsupportedEvents(cls):
with open("randomfile.json") as file:
return json.load(file)
supportedEvents = []
unsupportedEvents = getUnsupportedEvents()
I want to set the class attribute unsupportedEvent
using the classmethod getUnsupportedEvents()
, but when I attempt to do so in the above way, I get the following error:
unsupportedEvents = getUnsupportedEvents()
TypeError: 'classmethod' object is not callable
This seems really simple, am I just overlooking something really easy?
You are trying to use a class method before the class is fully defined. You must delay the call after the definition:
class exampleClass:
@classmethod
def getUnsupportedEvents(cls):
with open("randomfile.json") as file:
return json.load(file)
supportedEvents = []
exampleClass.unsupportedEvents = exampleClass.getUnsuportedEvents()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.