David542
David542

Reputation: 110257

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).

Upvotes: 0

Views: 74

Answers (1)

Solomon Ucko
Solomon Ucko

Reputation: 6109

@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)

Upvotes: 5

Related Questions