Search code examples
pythonclass-method

Python classmethod outside the class


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?


Solution

  • The decorator produces a classmethod object. Such objects are descriptors (just like staticmethod, 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:

    ClassObject.attribute_name = do_something
    

    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 the classmethod descriptor without invoking it:

    ClassObject.__dict__['do_something']
    

    as straight attribute access would cause Python to call the descriptor.__get_ method for you, returning a bound method:

    >>> class Foo(object):
    ...     @classmethod
    ...     def bar(cls):
    ...         print 'called bar on {}'.format(cls.__name__)
    ... 
    >>> Foo.bar
    <bound method type.bar of <class '__main__.Foo'>>
    >>> Foo.bar()
    called bar on Foo
    >>> Foo.__dict__['bar']
    <classmethod object at 0x1076b20c0>
    >>> Foo.__dict__['bar'].__get__(None, Foo)
    <bound method type.bar of <class '__main__.Foo'>>
    >>> Foo.__dict__['bar'].__get__(None, Foo)()
    called bar on Foo