This is an academic question, more than a practical one. I'm trying to delve into the foundations of Python, and I wonder: could I implement the staticmethod
and classmethod
decorators in pure Python if I wanted to?
For staticmethod
maybe I could keep a reference to the original function and call it omitting the first argument?
For classmethod
maybe I could keep a reference to the original function and call it passing the type of the first argument, rather than the argument itself? (How would I handle it being called directly on the class?)
Again, it's not that I want to actually implement it in my programs; I want to learn how the language works from it. If it's possible to do I would really appreciate code samples. If not, I would appreciate explanations why it can't be done theoretically. Thanks!
Edit: Thanks for the answer and for the reference to the descriptor protocol! As a means to further extend my understanding of Python I'd like to ask two more things:
Could this be done without the descriptor protocol, for example by implementing the __ call __ special method in our classes?
Does the descriptor protocol work the same way in Python 2.7 and in Python 3.x?
Thanks again!
The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class.
The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.
staticmethods can be used when the code that belongs to a class doesn't use the object itself at all. Python doesn't have to instantiate a bound method for each object we instantiate. Bound methods are objects too, and creating them has a cost. Having a static method avoids that.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With