【问题标题】:What is the purpose of classmethod in this code?这个代码中的ClassMethod的目的是什么?
【发布时间】:2010-12-29 08:31:59
【问题描述】:

在 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 在这个代码示例中做了什么。有人能解释一下它的作用和使用方法吗?

【问题讨论】:

标签: python


【解决方案1】:

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'>,)

如您所见,无论您是直接定义它还是使用装饰器语法定义它,也无论您在类还是实例上调用它,classmethod 始终接收类作为其第一个参数。

classmethod 的主要用途之一是定义替代构造函数

>>> class y(object):
...   def __init__(self, astring):
...     self.s = astring
...   @classmethod
...   def fromlist(cls, alist):
...     x = cls('')
...     x.s = ','.join(str(s) for s in alist)
...     return x
...   def __repr__(self):
...     return 'y(%r)' % self.s
...
>>> y1 = y('xx')
>>> y1
y('xx')
>>> y2 = y.fromlist(range(3))
>>> y2
y('0,1,2')

现在,如果您将y 子类化,classmethod 将继续工作,例如:

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

【讨论】:

  • 这不是替代构造函数,这是工厂方法。
  • @t3chb0t 它是一种工厂方法,可用作替代构造函数。
  • 同意@t3chb0t,这是string representation of the object的替代方案。本例中 y 类和 k 类的对象似乎具有相同的结构。
【解决方案2】:

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

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

MyClass._new_instance("blah")

【讨论】:

  • 作为装饰器也比较常用:@classmethod def _new_instance(cls, blah):
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 2021-02-06
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多