创建同时是实例和类方法的方法 [英] Creating a method that is simultaneously an instance and class method
问题描述
在 Python 中,我希望能够创建一个既可以作为类函数又可以作为实例方法运行的函数,但可以更改行为.此用例用于一组可序列化的对象和类型.举个例子:
<预><代码>>>>类事物(对象):#...>>>Thing.to_json()'一个'>>>东西().to_json()'乙'我知道,鉴于 Python 源代码中 funcobject.c 中 classmethod() 的定义,这看起来使用 C 模块很简单.有没有办法在 python 中做到这一点?
谢谢!
借助描述符的提示,我可以使用以下代码来完成:
类组合方法(对象):def __init__(self, method):self.method = 方法def __get__(self, obj=None, objtype=None):@functools.wraps(self.method)def _wrapper(*args, **kwargs):如果 obj 不是 None:返回 self.method(obj, *args, **kwargs)别的:返回 self.method(objtype, *args, **kwargs)返回_包装器
谢谢亚历克斯!
当然,您只需要定义自己的描述符类型.关于 Python 描述符的优秀教程这里.
In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example:
>>> class Thing(object):
#...
>>> Thing.to_json()
'A'
>>> Thing().to_json()
'B'
I know that given the definition of classmethod() in funcobject.c in the Python source, this looks like it'd be simple with a C module. Is there a way to do this from within python?
Thanks!
With the hint of descriptors, I was able to do it with the following code:
class combomethod(object):
def __init__(self, method):
self.method = method
def __get__(self, obj=None, objtype=None):
@functools.wraps(self.method)
def _wrapper(*args, **kwargs):
if obj is not None:
return self.method(obj, *args, **kwargs)
else:
return self.method(objtype, *args, **kwargs)
return _wrapper
Thank you Alex!
Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.
这篇关于创建同时是实例和类方法的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!