ajrlewis
ajrlewis

Reputation: 3058

Class variable that is an instance of itself

Is something like this possible?

class Foo:
    BAR = Foo("bar")
    def __init__(self, name):
        self.name = name

Currently this yields NameError: name 'Foo' is not defined.

Upvotes: 2

Views: 1012

Answers (1)

chepner
chepner

Reputation: 532003

No. annotations only applies to variable and function annotations. Until the class statement as been completely executed, there is no class Foo to instantiate. You must wait until after Foo is defined to create an instance of it.

class Foo:
    def __init__(self, name):
        self.name = name

Foo.BAR = Foo("bar")

You can always initialize BAR = None, then change the value of the attribute after the class is defined.

class Foo:
    BAR = None  # To be a Foo instance once Foo is defined
    ...

Foo.BAR = Foo("bar")  # Fulfilling our earlier promise

That might be desirable for documentation purposes, to make it clearer in the definition that Foo.BAR will exist, though with a different value. I can't think of a situation where that would be necessary, though.

Upvotes: 6

Related Questions