可以在纯Python中实现staticmethod和classmethod装饰器吗? [英] Can the staticmethod and classmethod decoraters be implemented in pure Python?
问题描述
这是一个学术问题,而不是实际问题。我正在尝试研究Python的基础,但我想知道:我可以实现 staticmethod
和 classmethod
装饰器吗
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?
对于 staticmethod
,也许我可以保留对原始函数的引用并调用
For staticmethod
maybe I could keep a reference to the original function and call it omitting the first argument?
对于 classmethod
也许我可以保留对原始函数的引用并称为传递第一个参数的类型,而不是参数本身? (我怎么处理直接在课堂上被调用的呢?)
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!
编辑::感谢您的回答和对描述符协议的引用!为了进一步扩展我对Python的理解,我想再问两件事:
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:
-
描述符协议,例如通过在类中实现__ call __特殊方法?
Could this be done without the descriptor protocol, for example by implementing the __ call __ special method in our classes?
描述符协议在Python 2.7和Python中是否以相同的方式工作3.x?
Does the descriptor protocol work the same way in Python 2.7 and in Python 3.x?
再次感谢!
推荐答案
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
并且:
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
这篇关于可以在纯Python中实现staticmethod和classmethod装饰器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!