Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I am not answering what you asked - but below shows what could be a decorator equivalent to <code>classmethod</code>, written in Pure Python - since the one in the source code is in C, inside <a href="http://hg.python.org/cpython/file/8527427914a2/Objects/funcobject.c#l589" rel="nofollow noreferrer"><code>Python-2.7.2/Objects/funcobject.c</code></a> as Mishna puts in his answer.</p> <p>So, the idea of class methods is to use the "descriptor" mechanism, as described in <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="nofollow noreferrer">Python's data model</a> - and make it so that the <code>__get__</code> method does return a function object that when called, will call the original method with the first argument pre-filled:</p> <pre><code>class myclassmethod(object): def __init__(self, method): self.method = method def __get__(self, instance, cls): return lambda *args, **kw: self.method(cls, *args, **kw) </code></pre> <p>And on Python console:</p> <pre><code>&gt;&gt;&gt; class MyClass(object): ... @myclassmethod ... def method(cls): ... print cls ... &gt;&gt;&gt; &gt;&gt;&gt; m = MyClass() &gt;&gt;&gt; m.method() &lt;class '__main__.MyClass'&gt; &gt;&gt;&gt; </code></pre> <p><strong>* EDIT - Update *</strong></p> <p>The O.P. further asked "If I wanted the decorator to also accept a parameter what would be the proper format for init? " -</p> <p>In that case it is not only <code>__init__</code> which has to be changed - a decorator that accepts configuration parameters is actually called in "two stages" - the first one annotate the parameters, and returns a callable - the second call accepts only the function which will actually be decorated.</p> <p>There are a few ways to do it - but I think the most straightforward is to have a function that returns the class above, like in:</p> <pre><code>def myclasmethod(par1, par2, ...): class _myclassmethod(object): def __init__(self, method): self.method = method def __get__(self, instance, cls): # make use of par1, par2,... variables here at will return lambda *args, **kw: self.method(cls, *args, **kw) return _myclassmethod </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload