Python 获取字段作为参数的函数
我想知道是否有可能创建一个以属性作为参数的类函数(不知道如何命名) 例如:Python 获取字段作为参数的函数,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:
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”中检索“市场”,然后从结果中检索“类型”,然后尝试将其作为函数调用。这给了我们一个点,在这里我们可以中断递归并实际返回结果
快速脏的解决方案可能如下所示:
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
如果需要更高级的功能,那么可以扩展helper类,因为在当前状态下,它只能返回一个键列表。这将导致无限递归。
\uuu getattr\uuuu
的常用语法/用法在《你想要更像getattr(self.url,key)
的东西吗?这是一个强类型的背景,但我会尽量避免这种动态代码,因为它更难测试,IDE无法智能地处理它,对支持API的细微更改会使用CrestAPI推回到代码中(因此它是过度耦合和脆弱的)。问题是self.url是嵌套dict,它也可以再次返回嵌套dict,因此我希望能够使用.market.types作为dict键。您的自定义\uu getattr\uuu
只能通过'market'
调用<代码>'types'由它返回的dict处理(如果您执行getattr(self.url,key)
)。这可能就是你想要做的。