Can stylish class-class methods and decoders be implemented in pure Python?

This is an academic question, more than practical. I'm trying to delve into the basics of Python, and I wonder: can I implement staticmethod and classmethod in pure Python if I want?

For staticmethod maybe, I could save a reference to the original function and call it omitting the first argument?

For classmethod maybe, I could save a reference to the original function and call it passing the type of the first argument, and not the argument itself? (How can I handle it being called directly in the class?)

Again, this is not what I want to put into practice in my programs; I want to know how the language works on it. If it were possible, I would really appreciate the code samples. If not, I will be grateful for the explanation of why this cannot be done theoretically. Thanks!

Edit: Thanks for the response and for the link to the descriptor protocol! As a means of further expanding my understanding of Python, I would like to ask two more things:

  • Is it possible to do this without a descriptor protocol, for example, by implementing the special __ call __ method in our classes?

  • Does the handle protocol work the same in Python 2.7 and in Python 3.x?

Thanks again!

+8
python decorator static-methods class-method
source share
2 answers

There are examples in the docs :

 class StaticMethod(object): "Emulate PyStaticMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return self.f 

and

 class ClassMethod(object): "Emulate PyClassMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, klass=None): if klass is None: klass = type(obj) def newfunc(*args): return self.f(klass, *args) return newfunc 
+10
source share

You should accept JF Sebastian's answer as it directly answers your question, but asking this question means you want to learn about the descriptor protocol you can read about here , which is used to implement these and other important Python internal components (and may be useful in your own code when used sparingly). property , and the usual methods associated with it are other things that are written using the descriptor protocol.

You have to check it, it is not so easy when you first read about it, but it will click.

+1
source share

All Articles