Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class instance as static attribute

Python 3 doesn't allow you to reference a class inside its body (except in methods):

class A:
    static_attribute = A()

    def __init__(self):
        ...

This raises a NameError in the second line because 'A' is not defined.

Alternatives

I have quickly found one workaround:

class A:
    @property
    @classmethod
    def static_property(cls):
        return A()

    def __init__(self):
        ...

Although this isn't exactly the same since it returns a different instance every time (you could prevent this by saving the instance to a static variable the first time).

Are there simpler and/or more elegant alternatives?

EDIT: I have moved the question about the reasons for this restriction to a separate question

like image 333
0x539 Avatar asked Jul 05 '26 18:07

0x539


1 Answers

The expression A() can't be run until the class A has been defined. In your first block of code, the definition of A is not complete at the point you are trying to execute A().

Here is a simpler alternative:

class A:
    def __init__(self):
        ...

A.static_attribute = A()
like image 54
khelwood Avatar answered Jul 08 '26 06:07

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!