猿问

如何将文件结构表示为 python 对象

我试图找到一种将文件结构表示为 python 对象的方法,这样我就可以轻松获得特定路径,而无需输入字符串。这适用于我的情况,因为我有一个静态文件结构(不改变)。


我想我可以将目录表示为类,并将目录中的文件表示为类/静态变量。


我希望能够浏览 python 对象,以便它返回我想要的路径,即:


print(FileStructure.details.file1) # root\details\file1.txt

print(FileStructure.details) # root\details

我从下面的代码中得到的是:


print("{0}".format(FileStructure())) # root

print("{0}".format(FileStructure)) # <class '__main__.FileStructure'>

print("{0}".format(FileStructure.details)) # <class '__main__.FileStructure.details'>

print("{0}".format(FileStructure.details.file1)) # details\file1.txt

我到目前为止的代码是......


import os 


class FileStructure(object): # Root directory

    root = "root"


    class details(object): # details directory

        root = "details"

        file1 = os.path.join(root, "file1.txt") # File in details directory

        file2 = os.path.join(root, "file2.txt") # File in details directory


        def __str__(self):

            return f"{self.root}"


    def __str__(self):

        return f"{self.root}"

我不想必须实例化类才能完成这项工作。我的问题是:


如何调用类对象并让它返回一个字符串而不是 < class ....> 文本

我怎样才能让嵌套类使用它们的父类?


江户川乱折腾
浏览 166回答 2
2回答

小唯快跑啊

预先:这是一个糟糕的解决方案,但它只需少量更改即可满足您的要求。基本上,您需要实例__str__才能工作,因此这会欺骗使用装饰器语法将您的类声明更改为已声明类的单例实例化。由于从嵌套类中隐式引用外部类是不可能的,因此该引用是显式执行的。并且可以复用__str__,file1并且file2被做成@propertys这样他们就可以使用实例的str形式details来构建自己。@object.__new__class FileStructure(object): # Root directory&nbsp; &nbsp; root = "root"&nbsp; &nbsp; @object.__new__&nbsp; &nbsp; class details(object): # details directory&nbsp; &nbsp; &nbsp; &nbsp; root = "details"&nbsp; &nbsp; &nbsp; &nbsp; @property&nbsp; &nbsp; &nbsp; &nbsp; def file1(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return os.path.join(str(self), 'file1')&nbsp; &nbsp; &nbsp; &nbsp; @property&nbsp; &nbsp; &nbsp; &nbsp; def file2(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return os.path.join(str(self), 'file2')&nbsp; &nbsp; &nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return f"{os.path.join(FileStructure.root, self.root)}"&nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; return f"{self.root}"再说一遍:虽然这确实会产生您想要的行为,但这仍然是一个糟糕的解决方案。我强烈怀疑您在这里遇到了 XY 问题,但这回答了所问的问题。
随时随地看视频慕课网APP

相关分类

Python
我要回答