2014-09-12 5 views
0

나는이 상황을 파이썬 (피라미드 프레임 워크 사용)에서 조건을 확인하려고합니다. 동적 __parent__.__parent__...을 표현하기위한 더 파이썬 방법 (문법 설탕 바로 가기)이,중첩 된 셀에 대한 파이썬 단축키 (구문 설탕) .__ 부모 __.__ 부모 _

if some_condition: 
    value = self.__parent__.__parent__.__parent__.method() 
else: 
    value = self.__parent__.__parent__.method() 

질문은 다음과 같습니다 코드인가?

나는이 같은 파이썬 구문이 있음을 알고 내 경우 유사한 동적 뭔가

value1, value2, value3 = (None,) * 3 

있습니까? Google, Python 문서, Reddit 소스 코드, Open Stack 소스 코드에서 검색했으며 검색에 2 일을 소비하므로 여기에서 질문하기로 결정했습니다.

답변

1

필자가 아는 한 파이썬에는 그러한 구문이 없습니다. 를 반복

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() 

UPDATE : 그의 대답에 @Dunes에서 제공 코드가 인덱스에 의해 조상을 얻을 수있는 또 다른 좋은 방법입니다.

+0

내가 find_interface 알고,하지만 난 그리워 몇 가지 구문 바로 가기가 있는지 알 필요가 있었다. 어쨌든 유연한 동적 인 것이 없다고 나는 생각한다. – intel

+0

@intel 내가 말했듯이, 나는 그런 구문을 모른다. – Vladimir

3

부모 체인이 마음에 들지 않으면 주어진 깊이에서 노드를 가져 오는 도우미 메서드를 작성할 수 있습니다. 이 경우 가독성이 떨어질 수 있습니다.

예 :

def get_parent(item, depth): 
    original_depth = depth 
    try: 
     while depth: 
      item = item.__parent__ 
      depth -= 1 
     return item 
    except AttributeError: 
     raise AttributeError("No parent node found at depth {}".format(
      original_depth-depth)) 

사용법 :

get_parent(self, 3).method() 
관련 문제