2

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?

3
  • This code should give a NameError for getUnsupportedEvents Commented May 7, 2020 at 9:38
  • If you want to assign inside the class just drop parenthesis unsupportedEvents = getUnsuportedEvents Commented May 7, 2020 at 9:41
  • @dhentris that would bind the function to the variable, which isn't what I want. I want it to execute and return the value of the function to be stored as a class attribute Commented May 7, 2020 at 10:11

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

If I was to import this class into my main program, would issues not arise as that line of code is outside the class?
You load modules and import symbols. In order to import the class, the module will be loaded and the line of code will be executed. Of course it has to be in the same module as the class definition after that definition.
Would the entire module be loaded even if I were to import specific classes from the module, i.e. ``` from exampleModule import exampleClass``` where exampleModule has several classes.
Exactly. That is the reason why I said you load (full) modules and import (some) symbols. In fact from mod import symb first loads the full mod module and then import sym in the local (or module global) symbol table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.