python - 使用一个函数来获取函数或常规属性的属性

标签 python python-3.x getattr getattribute

我有以下代码:

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())

是否有更短、更易于维护的方法来实现这样的功能?谢谢。

最佳答案

解决方案1

您可以将length设为property :

class Thing(object):
    def __init__(self):
        self.legs = 4
    @property
    def length(self):
        return 6

>>> thing = Thing()
>>> thing.legs
4
>>> thing.length
6

如果你真的想使用你的函数:

def set_session_attribute(obj, attribute):
    return getattr(obj, attribute)

>>> set_session_attribute(thing, 'legs')
4
>>> set_session_attribute(thing, 'length')
6

如果你不能直接改变thing的来源,你可以在导入类之后做:

class Thing(object):
    def __init__(self):
        self.legs = 4
    def length(self):
        return 6

这里:

Thing.length2 = property(Thing.length)

>>> thing = Thing()
>>> thing.length2
6

解决方案2

或者,您可以检查属性是否可调用:

class Thing(object):
    def __init__(self):
        self.legs = 4
    def length(self):
        return 6

def set_session_attribute(obj, attribute):
    attr = getattr(obj, attribute)
    if hasattr(attr, '__call__'):  # may use `callable()`
        return attr()
    return attr

>> thing = Thing()
>>> set_session_attribute(thing, 'legs')
4
>>> set_session_attribute(thing, 'length')
6

关于python - 使用一个函数来获取函数或常规属性的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36411611/

相关文章:

python - 删除pandas字符串列中的重复字符?

python - 多线程 Python 应用程序和套接字连接的问题

python-3.x - 将填充查询插入添加到列表框

python - 滥用点语法来方便地访问 Python 中的 API

python - 更改类中的 kivy 小部件属性

python - 玛雅 python : getting the position of selected object using getAttr

python - 避免昂贵的 __init__ 是使用 __new__ 的好理由吗?

python - 将感兴趣的图像点转换为坐标

python - 如果超过一半的值是零,则删除行 - Python

python - 用条件替换数据框值