可以将类方法创建为非装饰器吗?

Dav*_*542 0 python decorator class-method python-3.x

假设我有以下课程:

class Item:
    def __init__(self, string=''):
        self.string = string
    @classmethod
    def from_string(cls, string):
        return cls(string=string)
Run Code Online (Sandbox Code Playgroud)

上述情况下的classmethod并不是必需的,因为我可以轻松地调用Item(string='asdf')而不是Item.from_string(string='asdf'),但是我只是以它为例。

是否有可能连接任意类方法的类本身以外?例如,类似:

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

classmethod(from_string(Item, "asdf"))
Run Code Online (Sandbox Code Playgroud)

或者,将其编写如下:

class Item:
    def __init__(self, string=''):
        self.string = string
    from_string = classmethod(f)
    def f(string):
        return Item(string)
Run Code Online (Sandbox Code Playgroud)

基本上,我想更多地了解装饰器,以及如何在其正常上下文之外使用它们(以了解其幕后工作)。

Sol*_*cko 5

@classmethod
def from_string(cls, string):
    return cls(string=string)
Run Code Online (Sandbox Code Playgroud)

相当于

def from_string(cls, string):
    return cls(string=string)
from_string = classmethod(from_string)
Run Code Online (Sandbox Code Playgroud)
class Item:
    def __init__(self, string=''):
        self.string = string
    from_string = classmethod(f)
    def f(string):
        return Item(string)
Run Code Online (Sandbox Code Playgroud)

应该重新安排为

class Item:
    def __init__(self, string=''):
        self.string = string
    from_string = classmethod(f)
    def f(string):
        return Item(string)
Run Code Online (Sandbox Code Playgroud)

  • 在某些情况下(主要是怪异的元类),这种等效并不“足够”成立,因为装饰器版本仅对`from_string`执行一次赋值,而非装饰器版本执行对“ from_string”的赋值。对于大多数目的,这些版本可以认为是等效的。 (3认同)