Nice programing

Python의 순환 종속성

nicepro 2020. 12. 7. 20:41
반응형

Python의 순환 종속성


나는 두 개의 파일이 node.pypath.py두 개의 클래스를 정의, Node그리고 Path각각.

오늘까지 정의 PathNode객체 참조 했기 때문에

from node.py import *

에서 path.py파일.

그러나 오늘 Node부터 Path객체 를 참조 하는 새로운 메서드를 만들었습니다 .

가져 오려고 할 때 문제가 발생 path.py했습니다. 시도했는데 프로그램이 실행되고 Path를 사용 하는 메서드를 호출 할 때 정의되지 않은 Node예외가 발생했습니다 Node.

어떡하죠?


Python 모듈 가져 오기는 Python 에서 순환 가져 오기를 설명하는 훌륭한 기사입니다.

이를 수정하는 가장 쉬운 방법은 경로 가져 오기를 노드 모듈의 끝으로 이동하는 것입니다.


한 가지 다른 접근 방식은 두 모듈 중 하나를 다른 곳에서 필요한 함수에서만 가져 오는 것입니다 . 물론 이것은 하나 또는 적은 수의 기능에서만 필요한 경우 가장 잘 작동합니다.

# in node.py 
from path import Path
class Node 
    ...

# in path.py
class Path
  def method_needs_node(): 
    from node import Node
    n = Node()
    ...

다른 종속 클래스의 생성자에서 종속성 중 하나를 선언하여 순환 종속성을 끊는 것을 선호합니다. 내 관점에서 이것은 코드를 깔끔하게 유지하고 종속성이 필요한 모든 메서드에 쉽게 액세스 할 수 있도록합니다.

그래서 제 경우에는 서로 의존하는 CustomerService와 UserService가 있습니다. 다음과 같이 순환 종속성을 끊습니다.

class UserService:

    def __init__(self):
        # Declared in constructor to avoid circular dependency
        from server.portal.services.admin.customer_service import CustomerService
        self.customer_service = CustomerService()

    def create_user(self, customer_id: int) -> User:
        # Now easy to access the dependency from any method
        customer = self.customer_service.get_by_id(customer_id)

참고 URL : https://stackoverflow.com/questions/894864/circular-dependency-in-python

반응형