【发布时间】:2016-04-04 19:48:46
【问题描述】:
我有以下代码:
In [38]: %paste
def set_session_attribute(obj, attribute):
if attribute.endswith('()'):
attribute = attribute.replace('()', '')
return getattr(obj, attribute)()
else:
return getattr(obj, attribute)
class Thing(object):
def __init__(self):
self.legs = 4
def length(self):
return 6
## -- End pasted text --
In [39]: x = Thing()
In [40]: y = set_session_attribute(x, 'legs')
In [41]: y
Out[41]: 4
In [42]: z = set_session_attribute(x, 'length()')
In [43]: z
Out[43]: 6
这是因为使用 "length()" 调用无效 (AttributeError, no attribute length())
有没有一种更短、更易于维护的方法来制作这样的函数?谢谢。
【问题讨论】:
标签: python python-3.x getattr getattribute