【发布时间】:2017-07-22 23:19:08
【问题描述】:
我正在尝试管理通过 Python 对象的层次结构创建的目录树。我想序列化 JSON 中的顶级对象,这样我就可以与用户共享两件事: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
我对现在更新 Top 对象中路径的工作方式感到满意:
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?
如何让最后一行改为打印“~/Downloads/Top/InTop”?
也许有更好的方法来管理这样的相对文件路径 - 如果有,请告诉我。
提前致谢!
【问题讨论】:
标签: python oop properties attributes