python - 获取字段作为参数的函数

标签 python

我想知道是否可以创建一个将属性作为参数的类函数(不知道如何命名)

示例:

class CrestAPI(object):
    def __init__(self):
        self.base_url = 'https://public-crest.eveonline.com/'
        self.urls = get_json(self.base_url)

    def __getattr__(self, key):
        try:
            getattr(self, key)
        except AttributeError:
            print key

api = CrestAPI()
api.market.types

其中 api.market.types 应该打印类似 ['market', 'types'] 的内容 因此,当该属性不存在时,我可以使用这些参数运行一些函数

最佳答案

这有点棘手。

在您的示例中,Python 将首先尝试从对象“api”中检索属性“market”,然后从第一步中收到的任何内容中检索属性“types”。所以本质上你需要一个迭代解决方案。

然而,对于迭代解决方案来说,关键问题是何时停止。并且您的示例中没有任何内容可以告诉代码“是的,解析在此停止”。

但是,可以使用稍微不同的语法,例如:

api = CrestAPI()
parsed_url = api.market.types()

在这种情况下,Python将从“api”中检索“market”,然后从结果中检索“types”,然后尝试将其作为函数调用。这为我们提供了可以打破递归并实际返回结果的点。

一个快速而肮脏的解决方案可能如下所示:

class RecursiveRetrievalHelper(object):

    __items = None

    def __init__(self, first_item):
        self.__items = [first_item]

    def __getattr__(self, item):
        self.__items.append(item)
        return self

    # One possible way to break the iteration
    def __call__(self, *args, **kwargs):
        return self.__items

    # Another possible way to break the iteration
    def __iter__(self):
        return iter(self.__items)

    # This is mostly for debugging and console
    def __repr__(self):
        return repr(self.__items)


class MainClass(object):
    def __getattr__(self, item):
        return RecursiveRetrievalHelper(item)


if __name__ == '__main__':
    this_api = MainClass()
    print this_api.has.some.weird.complicated.path()     # Uses __call__()
    print list(this_api.has.some.weird.complicated.path) # Uses __iter__()
    for url_part in this_api.has.some.weird.complicated.path: # Uses __iter__() again
        print url_part,
    print

脚本输出:

['has', 'some', 'weird', 'complicated', 'path']
['has', 'some', 'weird', 'complicated', 'path']
has some weird complicated path

如果您需要更高级的功能,您可以扩展帮助器类,因为在当前状态下,它只能返回一个键列表。

关于python - 获取字段作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031343/

相关文章:

python - sqlite3.ProgrammingError : Incorrect number of bindings supplied. 当前语句使用2,并且提供了0

python - ndb to_dict 方法不包括对象的键

python - 使用装饰器在定义的函数上产生 NameError

python - 将 side_effect 与模拟一起使用时未调用异常

python - 解析嵌套的三元表达式

python - Pydev 调试器无法使用断点

python - python/matlab/simulink/maple 用户的 Modelica?

jquery - 如何使用 AJAX 接收作为 HTTP 请求传递的 Python Flask 中的参数的对象数组?

python - shell脚本替换?

python - 使用 FFMPEG 和 Python 编码视频时出现绿色条纹伪影