1

Is it possible to access a static method or attribute when assigning to a static attribute?

For example:

class Test:

    @staticmethod
    def fortytwo():
        return 42

    var = Test.fortytwo()

would raise NameError: name 'Test' is not defined

natonomo
  • 325
  • 1
  • 9
  • You can't do that with `@staticmethod` but it works if you 1. omit `@staticmethod` and 2.call `fortytwo()` instead of `Test.fortytwo()`. – kindall Aug 10 '18 at 18:15
  • You can also just do it outside the class body: `Test.var = Test.fortytwo()`. – juanpa.arrivillaga Aug 10 '18 at 18:18
  • @natonomo Are you aware that var = Test.fortytwo() is defined inside the class due to the indent? – Michael Scheffenacker Aug 10 '18 at 18:21
  • @MichaelScheffenacker yes that was the idea. The class this example represents is entirely static methods and attributes. I know the methods can access the attributes, I was hoping the opposite was true. – natonomo Aug 10 '18 at 18:27
  • And the link at the top (https://stackoverflow.com/a/12718272/2534715) did also not help you out? – Michael Scheffenacker Aug 10 '18 at 18:30
  • @natonomo a class with only static methods and attributes probably shouldn't be a class. The fundamental problem, though, is as implied by the error message, *the class object doesn't exist until the class definition is finished executing*. You cannot access the class namespace because it hasn't been created yet. You can just do it after the class definition though. – juanpa.arrivillaga Aug 10 '18 at 18:36
  • 2
    @MichaelScheffenacker no it did, I'm not sure why I couldn't find that when I was forming this question. I decided to convert the "static class" to a module, as that is the Pythonic way – natonomo Aug 10 '18 at 18:40

0 Answers0