AttributeError: 'instancemethod' object has no attribute 'short_description'

AttributeError: 'instancemethod' object has no attribute 'short_description'

我尝试更新方法的属性,但失败了:

class Activity(object):

    def my_method(self):
        return 'foo'
    my_method.short_description = 'old'
Activity.my_method.short_description = 'new'

异常:

    Activity.my_method.short_description = 'new'
AttributeError: 'instancemethod' object has no attribute 'short_description'

有没有办法更新my_method.short_description

这需要与 Python 2.7 配合使用。使用 Python 3.x 不会发生此异常。

我找到了这个解决方案:

import types


class Activity(object):

    def my_method(self):
        return 'foo'

    my_method.short_description = 'old'


# Activity.my_method.short_description = 'new'
# --> Exception

class UpdateableInstanceMethod():
    # Otherwise: 'instancemethod' object has no attribute 'short_description'
    def __init__(self, orig_method, short_description):
        self.orig_method = orig_method
        self.short_description = short_description

    def __call__(self, obj):
        return self.orig_method(obj)


Activity.my_method = types.MethodType(UpdateableInstanceMethod(
    Activity.my_method,
    'new'
), None, Activity)

assert Activity.my_method.short_description == 'new'
assert Activity().my_method.short_description == 'new'

assert Activity().my_method() == 'foo'
print('ok')