2017-03-03 3 views
0

파이썬 객체의 계층 구조를 통해 만들어진 디렉토리 트리를 관리하려고합니다. JSON의 최상위 객체를 직렬화하여 사용자와 2 가지 항목, 즉 JSON 파일과 디렉토리를 공유 할 수 있습니다. 나는 다른 사용자가 그 디렉토리를 가리킬 수 있기를 바랍니다. 그래서 여기에있는 문제는 다른 컴퓨터에서 바뀔 수있는 루트 디렉토리를 설정하는 것입니다. 톱 객체의 경로를 업데이트하기 위해 지금 나는 이것이 어떻게 작동하는지에 행복 해요다른 클래스 간의 클래스 속성 동적 업데이트

import os.path as op 
class Top(): 
    def __init__(self, root_dir): 
     self._root_dir = root_dir 

     intop = InTop(self.base_dir) 
     self.intop = intop 

    @property 
    def root_dir(self): 
     return self._root_dir 

    @root_dir.setter 
    def root_dir(self, path): 
     self._root_dir = path 

    @property 
    def base_dir(self): 
     return op.join(self.root_dir, 'Top') 

class InTop(): 
    def __init__(self, root_dir): 
     self._intop_dir = op.join(root_dir, 'InTop') 

    @property 
    def intop_dir(self): 
     return self._intop_dir 

    @intop_dir.setter 
    def intop_dir(self, path): 
     self._intop_dir = path 

: 여기

는 내가 지금 무슨의 예입니다

t = Top('~/projects/') 
print(t.root_dir) # ~/projects/ 
print(t.base_dir) # ~/projects/Top 

t.root_dir = '~/Downloads/' 
print(t.root_dir) # ~/Downloads/ 
print(t.base_dir) # ~/Downloads/Top 

을하지만,이 해당 변경 사항이 InTop 객체에 전파되는 방식은 무엇입니까?

t = Top('~/projects/') 
print(t.root_dir) # ~/projects/ 
print(t.base_dir) # ~/projects/Top 
print(t.intop.intop_dir) # ~/projects/Top/InTop 

t.root_dir = '~/Downloads/' 
print(t.root_dir) # ~/Downloads/ 
print(t.base_dir) # ~/Downloads/Top 
print(t.intop.intop_dir) # ~/projects/Top/InTop <--- How to update this? 

은 어떻게 마지막 줄은 "~/다운로드/톱/InTop"대신를 인쇄 할 수 있음을받을 수 있나요?

아마도 이와 같은 상대 파일 경로를 관리하는 더 좋은 방법이 있습니다. 그렇다면 알려주세요.

미리 감사드립니다.

t = Top('~/projects/') 
print(t.root_dir) # ~/projects/ 
print(t.top_dir) # ~/projects/Top 
print(t.intop.intop_dir) # ~/projects/Top/InTop 

t.root_dir = '~/Downloads/' 
print(t.root_dir) # ~/Downloads/ 
print(t.top_dir) # ~/Downloads/Top 
print(t.intop.intop_dir) # ~/Downloads/Top/InTop 
:

답변

0

그것이 out..just 최고 세터 이내에 설정하는 데 필요한 나타냈다

import os.path as op 
class Top(object): 
    def __init__(self, root_dir): 
     self._root_dir = root_dir 

     intop_obj = InTop(self.top_dir) 
     self.intop = intop_obj 

    @property 
    def root_dir(self): 
     return self._root_dir 

    @root_dir.setter 
    def root_dir(self, path): 
     self._root_dir = path 
     self.intop.top_dir = self.top_dir 

    @property 
    def top_dir(self): 
     return op.join(self.root_dir, 'Top') 

class InTop(object): 
    def __init__(self, top_dir): 
     self._top_dir = top_dir 

    @property 
    def top_dir(self): 
     return self._top_dir 

    @top_dir.setter 
    def top_dir(self, top_dir): 
     self._top_dir = top_dir 

    @property 
    def intop_dir(self): 
     return op.join(self.top_dir, 'InTop') 

저를 가져옵니다 (또한 내 setter를 수정)