I want to get a specific class instance in the class's namespace. In C# this would look like this:
public struct Foo
{
public readonly static Bar = new Foo();
}
The only idea I have is to assign an instance right after the class definition (monkeypatch):
class Foo:
def __init__(self, spam):
self.spam = spam
Foo.bar = Foo(42)
But I want to provide instance in class definition, like this:
class Foo:
...
bar = Foo(42)
And interface like this:
from foo import Foo
bar = Foo.bar
The last line in definition gives a syntax error because Foo is not yet defined. Is there a way to overcome this constraint except monkeypatching class?
from How to define class field in Python that is an instance of a class?
No comments:
Post a Comment