Search code examples
pythonpython-3.xclassstatic-variables

Is there another way to have static variables depend on previous ones?


I would like to do something like this:

class Foo:
    A = some_constant
    B = Foo.A + 2
    ...

This doesn't work, because I am unable to reference Foo in the assignment of B.

I know using global variables would work:

A = some_constant
B = A + 2
class Foo:
    ...

Or assigning the variables after the class definition would work:

class Foo:
    ...
Foo.A = some_constant
Foo.B = Foo.A + 2

However, the first one does not provide the scoping that I would like, while the second one is rather clumsy in terms of my code organization, as it forces me to define these variables after the class definition.

Is there another way to solve this problem?


Solution

  • You can use the class variables directly (without the prefixing) in the declaration. But keep in mind that this is a one-time thing. Changing Foo.A later on will not update Foo.B.

    class Foo:
        A = 98
        B = A + 2