Location @classmethod

Where is the source code of the decorator class located in the python source code. In particular, it is difficult for me to find the exact file that it defined in version 2.7.2.

+7
source share
2 answers

I am not responding to what you requested, but the following shows what could be a decorator equivalent to the classmethod written in Pure Python, since the one that is in the source code is inside C, inside Python-2.7.2/Objects/funcobject.c , as Mishnah answers.

So, the idea of ​​class methods is to use the “descriptor” mechanism, as described in the Python data model — and make the __get__ method return a function object that, when called, will call the original method with the first argument pre-populated:

 class myclassmethod(object): def __init__(self, method): self.method = method def __get__(self, instance, cls): return lambda *args, **kw: self.method(cls, *args, **kw) 

And in the Python console:

 >>> class MyClass(object): ... @myclassmethod ... def method(cls): ... print cls ... >>> >>> m = MyClass() >>> m.method() <class '__main__.MyClass'> >>> 

* EDIT - update *

The OP further asked, “If I wanted the decorator to also accept a parameter, which would be the correct format for init?” -

In this case, it is necessary to change not only __init__ - the decorator that accepts the configuration parameters is actually called in "two stages" - the first annotates the parameters and returns the called - the second call is accepted only by the function that will actually be decorated.

There are several ways to do this, but I believe that the simplest task is a function that returns the class above, for example:

 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 
+11
source
 tar -zxf Python-2.7.2.tgz vim Python-2.7.2/Objects/funcobject.c ... 589 /* Class method object */ 590 591 /* A class method receives the class as implicit first argument, 592 just like an instance method receives the instance. 593 To declare a class method, use this idiom: 594 595 class C: 596 def f(cls, arg1, arg2, ...): ... 597 f = classmethod(f) 598 599 It can be called either on the class (eg Cf()) or on an instance 600 (eg C().f()); the instance is ignored except for its class. 601 If a class method is called for a derived class, the derived class 602 object is passed as the implied first argument. 603 604 Class methods are different than C++ or Java static methods. 605 If you want those, see static methods below. 606 */ ... 
+9
source

All Articles