3

I want to initialize class member with use class method but not know how to call it.

Can you suggest some solution - maybe it is very trivial but I can not find solution?

This code will not work - I do not why?

class X(object):
  @staticmethod
  def __Y():
    return 1

  CONSTANT = __Y()


x = X()
print x.CONSTANT

This will work but I need use call method to initialize class members.

class X(object):
  CONSTANT = 1

x = X()
print x.CONSTANT

Note, I am not want initialize object variables but class variable.

0

1 Answer 1

7

Drop the @staticmethod decorator and the first approach will work as well. You don't need staticmethod just to call a function inside a class statement.

Since that way the function will not be usable when called from class instances, it is an idiom to also remove it after use. In your example:

class X(object):
    def __y():
      return 1

    CONSTANT = __y()
    # ... other uses of __y, if any
    del __y

To understand why your approach didn't work, consider what staticmethod does. It wraps a normal function into a descriptor object that, when retrieved from the class, produces the original function unchanged, i.e. without the usual "bound method" semantics. (Retrieving a normal def function from an instance or a class would get you a bound method that automagically inserts self as the first argument.)

However, the descriptor returned by staticmethod is itself not callable, its sole function is to produce the callable object when accessed through the class or instance. Proposals to make the staticmethod descriptor callable were rejected because such use of staticmethod is erroneous in the first place.

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

6 Comments

Just curious, Dropping @staticmethod will turn def __Y() to def __Y(self), right? How is it possible to call the method without instantiating the class? In this case, CONSTANT = __Y(X())?
@Bibhas No, the insertion of self only happens when you access __Y through class or instance. If you call it from the class definition, a def is just a def. As no magic happens in the first place, you don't need @staticmethod to prevent it from happening.
@Bibhas Do call x.__Y() where x is some instantiated object. Instead, just call __Y() in the class definition will not lead __Y(self).
Oh. It's just another function. It doesn't become a method. Not accessible from the instance.
Doesn't calling x.__Y() pass x as the first argument always?
|

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.