Create static instances of a class inside said class in Python
- by Samir Talwar
Apologies if I've got the terminology wrong here—I can't think what this particular idiom would be called.
I've been trying to create a Python 3 class that statically declares instances of itself inside itself—sort of like an enum would work. Here's a simplified version of the code I wrote:
class Test:
A = Test("A")
B = Test("B")
def __init__(self, value):
self.value = value
def __str__(self):
return "Test: " + self.value
print(str(Test.A))
print(str(Test.B))
Writing this, I got an exception on line 2 (A = Test("A")). I assume line 3 would also error if it had made it that far. Using __class__ instead of Test gives the same error.
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in Test
NameError: name 'Test' is not defined
Is there any way to refer to the current class in a static context in Python? I could declare these particular variables outside the class or in a separate class, but for clarity's sake, I'd rather not if I can help it.
To better demonstrate what I'm trying to do, here's the same example in Java:
public class Test {
private static final Test A = new Test("A");
private static final Test B = new Test("B");
private final String value;
public Test(String value) {
this.value = value;
}
public String toString() {
return "Test: " + value;
}
public static void main(String[] args) {
System.out.println(A);
System.out.println(B);
}
}
This works as you would expect: it prints:
Test: A
Test: B
How can I do the same thing in Python?