使用输入值解析对象属性

Parsing Object Attribute with an Input Value

我开始认为这在 Python 中可能无法以 简单 的方式实现。无论是那个还是我似乎都无法很好地表达这个问题 Google 来解决它(或找到它的 Whosebug 答案)。

这里有一些精简代码可以帮助进行解释:

import numpy as np
class MyObject():
    def __getattr__(self, item):
            return getattr(np.eye(1), item)

这个简单的设置确保我每次调用属性时都能得到一个 numpy 数组(其中只有值 1)。这允许我调用 numpy 数组函数,例如 MyObject.sum() 最终 returns 一个整数值。

还有其他需要输入的函数,例如:MyObject.dot(AnotherNumPyArray)

到目前为止一切顺利...但是,我想在输出值不是严格的整数时执行一个特殊函数。即在第二种情况下,我得到一个 ndarray 作为输出。

我尝试部分解决这个问题:

import numpy as np
class MyObject():
    def __getattr__(self, item):
            func = getattr(np.eye(1), item)
            if type(func()) == np.ndarray:
                return func()*2
            else:
                return func

唯一的问题是,只有在调用函数没有输入参数的情况下,这才有效。我觉得我想在 if 语句中 运行 func(value) 但是,1) 我不知道如何传递值。并且 2) 一旦从 __getattr__ 返回,该值将尝试第二次解析。

您可以 return 包装方法,例如:

import numpy as np

class MyObject():

    def __getattr__(self, item):
        def wrapper(*args, **kwargs):
            func = getattr(np.ndarray(1), item)
            result = func(*args, **kwargs)
            if isinstance(result, np.ndarray):
                return result * 2
            return result
        return wrapper

此处 wrapper 将传入调用委托给 np.ndarray(1) 上的方法,并根据需要处理 returned result