3

我正在寻求有关在 Python 中表示没有符号链接的文件目录的优雅设计的建议,我可以在其中查询“属于”方面的关系(例如 G 是 /A/B/C 的子目录)。我目前的想法是朝着这个方向发展:

给定一个根路径,我os.path.walk()它自上而下。两个类代表我感兴趣的节点类型,我跟踪父子关系。

class ADir(object):
    def __init_(self, name, parent=None):
        self.name = name
        self.parent = parent
        self.children = []
    def add_child(self, id):
        self.children.append(id)

class AFile(object):
    def __init_(self, name, parent=None):
        self.name = name
        self.parent = parent

我将不得不重新实现对现有目录的检查、为我提供目录/文件位置的函数等。这一切都开始感觉非常像是对现有的通用树算法的重新实现。

通过 StackExchange、Google 等进行搜索会产生许多不同的方法。我发现没有一个似乎利用了给定目录结构的自然边界。

任何关于讨论、博客条目和代码的想法和指针都值得赞赏。

4

1 回答 1

2

当今语言中树结构的问题在于很难创建一种结构来适应所有语言。有很多方法可以构建三元组(有或没有父指针,子项可以是对(二叉树或红黑树)或列表(有或没有查找键的索引)。

虽然可以为所有这些定义遍历算法,但每个算法都需要不同的实现。

Then we have the problem to look up elements in the tree. Do we work by index (pretty useless in binary trees)? Some identifier? What type should the identifier have? How do we build paths from those identifiers? How do we represent relative paths?

Which is why we have maps and lists built into many modern languages but no trees. To my knowledge, Scala is one of the few OO languages which support the concept of a generic tree type but only binary trees and even those are somewhat odd.

On top of that, most OO languages don't support enough ways to build classes from fragments of existing classes. You can inherit (but then you get everything), multiple inherit (even more problems), mix in (some features of multiple inheritance without some of the drawbacks). But I'm really missing a feature which says: take method x() from type Foo and method y() from Bar to build Baz.

Without that, an OO based tree base class would need a lot of tweaking for your specific use case while directly implementing the same function would need the same amount (or even less) of code lines.

于 2012-03-07T08:52:48.710 回答