创建同时作为实例和类方法的方法 [英] Creating a method that is simultaneously an instance and class method

查看:96
本文介绍了创建同时作为实例和类方法的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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'

我知道给定Python源中funcobject.c中classmethod()的定义,这看起来像使用C模块一样简单.有没有办法从python内部执行此操作?

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?

谢谢!

在描述符的提示下,我可以使用以下代码来做到这一点:

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

谢谢亚历克斯!

推荐答案

当然,您只需要定义自己的描述符类型. 这里.

Sure, you just need to define your own descriptor type. There's an excellent tutorial on Python descriptors here.

这篇关于创建同时作为实例和类方法的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆