2
class A:
    x = A.initX()

    def __init__(self):
        self.y = A.initY()

    @staticmethod
    def initX():
        return 'X'

    @staticmethod
    def initY():
        return 'Y'

In the example above, I am not able to initialize the class A attribute X. The PyCharm editor is complaining of Unresolved reference 'A'. However, there does not seem to be a problem with initializing the instance attribute of Y using a similar way.

How do I initialize a class attribute using a static method from the same class?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    You can't (not from within `A` at least). Class attributes are defined at class definition time. As such, when `x = A.initX()` is executed, `A` does not "fully" exist yet, hence the error you recieve – DeepSpace Aug 08 '20 at 21:28
  • 6
    Run `A.x = A.initX()` after the whole definition of the class. – Klaus D. Aug 08 '20 at 21:30

1 Answers1

4

Your question is very similar to one I once asked titled Calling class staticmethod within the class body?. @DeepSpace's comment about how a class not existing during class definition time is the reason why.

Here's how to adapt the accepted answer to my question to your own situation (to define the class attribute within the class definition itself):

class A:
    def __init__(self):
        self.y = A.initY()

    @staticmethod
    def initX():
        return 'X'

    @staticmethod
    def initY():
        return 'Y'

    x = initX.__func__()  # Define class attribute.


print(A.x)  # -> X

As @Klaus D. commented, another way to do it is after the class is defined (outside the class body).

You don't encounter the problem initializing the instance attribute of Y because it occurs within a method of an instance of the class (so the class is fully defined at that point).

martineau
  • 119,623
  • 25
  • 170
  • 301