我嘗試更新方法的屬性,但失敗:
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 中不會發生此例外。
uj5u.com熱心網友回復:
我找到了這個解決方案:
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')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/462188.html
標籤:python-2.7
