我最近开始研究 Azure 的 SDK,但无法弄清楚为什么每个方法(由我测试过)都返回一个对象,而不是更“人性化”的东西,即列表或字典。
即:
list(compute_client.virtual_machines.list_all())
[<azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c190>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93c750>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93cad0>, <azure.mgmt.compute.compute.v2017_03_30.models.virtual_machine.VirtualMachine object at 0x7f637f93ced0>]
返回对象的好处是什么似乎很难与之交互,即我需要查找每个方法以找到返回值等等来处理列表,然后构建一个字典,这似乎是更多的工作需要。
我在一个 Microsoft blogs / githubs 中找到了这个方法:
def print_item(group):
"""Print a ResourceGroup instance."""
print("\tName: {}".format(group.name))
print("\tId: {}".format(group.id))
print("\tLocation: {}".format(group.location))
print("\tTags: {}".format(group.tags))
print_properties(group.properties)
这似乎非常低效 IMO 能够打印另一个方法的返回值。
有人可以建议为什么“对象列表”比“列表”更好,为什么不返回像 json 这样的东西。
请您参考如下方法:
简短回答:从任何实例调用 as_dict() 来获取对象的字典 View 。
答案很长:您获得的对象不仅仅是对初始 JSON 的简单包装。它是由 OpenAPI 生产的解析负责:
- 多态性
- 类型文字(日期时间、枚举等)
- XML/JSON。无论使用何种初始媒体,对象都是相同的,具体取决于端点的内容类型。
该对象本身包含多种方法,使其比简单的字典更复杂,例如 validate 以验证构建您的模型是否正确(即构建具有实时验证的网络表单)。
但是,作为消费者,Python 用户和您一样喜欢 dict,这就是 as_dict() 方法的目的。此方法甚至采用回调(访问者模式)以允许动态更改您将从该方法获得的字典序列化。
(我在微软的 Azure SDK Python 团队工作)
编辑:对于 list 操作,您将获得一个免费为您处理分页的 Python 迭代器。您甚至不知道何时获取第二页。对于内存消耗,当您将其包装到 list() 中时,您会立即将所有内容加载到内存中。如果您使用 for vm in compute_client.virtual_machines.list_all(),您将在内存中一次只有一页,不会更多。如果你只需要几个对象,如果你有很多 VM 来利用迭代器(无论使用 for 循环还是 next() 和StopIteration 异常)
