I have to use some Python library which contains file with various utilities: classes and methods. One of these methods is defined in the following way (I cannot put whole code):
@classmethod
def do_something(cls, args=None, **kwargs):
but this declaration is outside any class. How can I get access to this method? Calling by do_something(myClass)
gives an error: TypeError: 'classmethod' object is not callable
. What is the purpose of creating classmethods outside classes?
The decorator produces a
classmethod
object. Such objects are descriptors (just likestaticmethod
,property
and function objects).Perhaps the code is re-using that object as such a descriptor. You can add it to a class at a later time:
or you can explicitly call the
descriptor.__get__
method.By storing it as a global it is easier to retrieve; if you put it on a class you'd have to reach into the class
__dict__
attribute to retrieve theclassmethod
descriptor without invoking it:as straight attribute access would cause Python to call the
descriptor.__get_
method for you, returning a bound method: