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?
Use the @classmethod Decorator to Create a Static Class in Python. The @classmethod can make a method static to the class and not its object. It has several advantages over the @staticmethod decorator. It will also work with subclasses and can modify the class state.
Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.
Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.
Yes, definitely possible to write static variables and methods in python. Static Variables : Variable declared at class level are called static variable which can be accessed directly using class name.
After you defined the class, just add these two lines:
Test.A = Test("A")
Test.B = Test("B")
A class in Python is an object like any other and you can add new variables at any time. You just can't do it inside the class since it's not defined at that time (it will be added to the symbol table only after the whole code for the class has been parsed correctly).
While the Aaron's answer is the preferred way you can also use metaclasses:
>>> class TestMeta(type):
... def __init__(cls, name, bases, dct):
... cls.A = cls()
... cls.B = cls()
...
>>> class Test:
... __metaclass__ = TestMeta
...
>>> Test
<class __main__.Test at 0x7f70f8799770>
>>> Test.A
<__main__.Test object at 0x7f70f86f2e10>
>>> Test.B
<__main__.Test object at 0x7f70f86f2e90>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With