0

I have a code like this:

def my_func():
    pass

class MyClass():
   class_variable = my_func()
   pass

i = MyClass()

Since my_func is logically related to MyClass, and doesn't serve any purpose outside of it, I'd prefer to have something like that instead:

class MyClass():
   class_variable = my_func()

   def my_func():
       pass

i = MyClass()

The above doesn't work, of course, because my_func isn't defined yet at the time it's called. Is there some other way to assign a class variable from inside the class?

1 Answer 1

2

I'd personally keep my_func() outside the class. Sure, it may only be used for the class definition, but if it is not useful once the class is defined, it should not be part of the class API.

If the my_func() function should be used together with the class even after the class has been created, then you can still make this work with MyClass.my_func() being a static method. In that case define the function first before setting the class variable:

class MyClass():
   @staticmethod
   def my_func():
       pass

   class_variable = my_func.__func__()

The @staticmethod is not strictly necessary as at the time class_variable is set, my_func is still a local name in the class definition body.

However, since you are using it as as static function anyway, you may as well mark it as such. The advantage however is that MyClass.my_func() now also works.

Because a @staticmethod isn't going to bind outside of a class or instance attribute context, you do need to unwrap it first by accessing the wrapped function with the __func__ attribute.

Demo:

>>> class MyClass():
...    @staticmethod
...    def my_func():
...        return 'foobar'
...    class_variable = my_func.__func__()
... 
>>> MyClass.class_variable
'foobar'
>>> MyClass.my_func()
'foobar'
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.