0

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() ?

8
  • 1
    @Red they want my_class_variable to be a class variable, __init__ only works with instances Commented May 12, 2022 at 21:46
  • 1
    Does this answer your question? How to refer to class methods when defining class variables in Python? Commented May 12, 2022 at 21:49
  • 1
    @Red no, that is only if you create an instance Commented May 12, 2022 at 21:53
  • 2
    Anyway, the way to guarantee is simply to write MyClass.initialize() after your class definition. Commented May 12, 2022 at 21:54
  • 1
    @user1008636 I think you meant to respond to Red with regards to __init__. In any case, as I already pointed out, the simplest way to guaratnee initialize has been called is to call it. So after the class definition for class MyClass, just write MyClass.initialize() after. Commented May 13, 2022 at 0:40

1 Answer 1

0

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.