Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 这段代码中classmethod的用途是什么?_Python - Fatal编程技术网

Python 这段代码中classmethod的用途是什么?

Python 这段代码中classmethod的用途是什么?,python,Python,在django.utils.tree.py中: def _new_instance(cls, children=None, connector=None, negated=False): obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) 我不知道classmethod在这个代码示例中做了什么。

在django.utils.tree.py中:

def _new_instance(cls, children=None, connector=None, negated=False):
    obj = Node(children, connector, negated)
    obj.__class__ = cls
    return obj
_new_instance = classmethod(_new_instance)

我不知道
classmethod
在这个代码示例中做了什么。有人能解释一下它的功能和使用方法吗?

它可以对类而不是对象调用方法:

class MyClass(object):
    def _new_instance(cls, blah):
        pass
    _new_instance = classmethod(_new_instance)

MyClass._new_instance("blah")

classmethod
是一个装饰器,包装一个函数,您可以调用类或(等价地)其实例上的结果对象:

>>> class x(object):
...   def c1(*args): print 'c1', args
...   c1 = classmethod(c1)
...   @classmethod
...   def c2(*args): print 'c2', args
... 
>>> inst = x()
>>> x.c1()
c1 (<class '__main__.x'>,)
>>> x.c2()
c2 (<class '__main__.x'>,)
>>> inst.c1()
c1 (<class '__main__.x'>,)
>>> inst.c2()
c2 (<class '__main__.x'>,)
现在,如果您将
y
子类化,则classmethod将继续工作,例如:

>>> class k(y):
...   def __repr__(self):
...     return 'k(%r)' % self.s.upper()
...
>>> k1 = k.fromlist(['za','bu'])
>>> k1
k('ZA,BU')

它也更常用作装饰器:
@classmethod def\u new\u实例(cls,blah):
dupe:这不是一个可选构造函数,这是一个工厂方法。@t3chb0t它是一个工厂方法,可以作为替代构造函数使用。
>>> class k(y):
...   def __repr__(self):
...     return 'k(%r)' % self.s.upper()
...
>>> k1 = k.fromlist(['za','bu'])
>>> k1
k('ZA,BU')