我在Python(带有Pramramid框架)中遇到这种情况,我在这里尝试检查条件。这是代码:
if some_condition:
value = self.__parent__.__parent__.__parent__.method()
else:
value = self.__parent__.__parent__.method()
问题是,是否有更多的pythonic方法(语法糖快捷方式)用于__parent__.__parent__...
动态表示?
我知道有这样的Python语法:
value1, value2, value3 = (None,) * 3
我的案子有类似和动态的东西吗?我在Google中搜索,在Python文档中,在Reddit源代码中,在Open Stack源代码中进行搜索,并且花了2天的时间进行搜索,因此决定在此处进行询问。
据我所知,python中没有这样的语法。
但是,您确实可以实现自定义方法来获取父资源列表:
def find_ancestors(resource):
ancestors = [resource]
while hasattr(ancestors[-1], '__parent__'):
ancestors.append(ancestors[-1].__parent__)
return ancestors
或一种迭代它们的方法:
def iter_ancestors(resource):
yield resource
while hasattr(resource, '__parent__'):
resource = resource.__parent__
yield resource
另外,我不确定这种方式是否合适。我认为您应该看一下find_interface(..)方法,并以某种方式设法为您的资源定义适当的接口以找到它们。这样,您的代码将如下所示:
value = find_interface(self, ResourceA if some_condition else ResourceB).method()
更新: @Dunes在他的回答中提供的代码是通过祖先索引获得祖先的另一种好方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句