'How to initialize a python class variable outside of functions?
I have a python function:
class MyClass:
my_class_variable: str = Optional[None]
@classmethod
def initialize(cls):
cls.my_class_variable = cls.some_function()
I plan to use it like:
x = MyClass.my_class_variable
How can I guarantee have my_class_variable
to have initialized with a value, eg how can I force call initialize()
?
Solution 1:[1]
you could do something like :
def dec(cls):
cls.my_class_var = cls.some_func()
return cls
@dec
class MyClass:
my_class_var = ""
@classmethod
def some_func(cls):
return "Cool :)"
print(MyClass.my_class_var) --> Cool :)
Another option would be to use a metaprogramming, but as long as there is only one simple thing to do, I would use a decorator :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | baskettaz |