Search code examples
pythonpython-3.xdecoratorclass-method

Possible to create a classmethod as a non-decorator?


Suppose I have the following class:

class Item:
    def __init__(self, string=''):
        self.string = string
    @classmethod
    def from_string(cls, string):
        return cls(string=string)

The classmethod in the above case isn't necessary, as I could just as easily call Item(string='asdf') instead of Item.from_string(string='asdf'), but I'm just using it as an example.

Is it possible to attach an arbitrary classmethod outside of the class itself? For example, something like:

def from_string(cls, string):
    return cls(string=string)

classmethod(from_string(Item, "asdf"))

Or, to write it something like this:

class Item:
    def __init__(self, string=''):
        self.string = string
    from_string = classmethod(f)
    def f(string):
        return Item(string)

Basically, I'm trying to understand decorators a bit more and how they might be used outside of their normal context (to see what they do behind the scenes).


Solution

  • @classmethod
    def from_string(cls, string):
        return cls(string=string)
    

    is equivalent to

    def from_string(cls, string):
        return cls(string=string)
    from_string = classmethod(from_string)
    

    class Item:
        def __init__(self, string=''):
            self.string = string
        from_string = classmethod(f)
        def f(string):
            return Item(string)
    

    should be rearranged to

    class Item:
        def __init__(self, string=''):
            self.string = string
        def f(string):
            return Item(string)
        from_string = classmethod(f)