【问题标题】:Python add a method to print the content of an object (in a tree structure)Python添加一个打印对象内容的方法(在树结构中)
【发布时间】:2021-11-29 14:01:37
【问题描述】:

这是我必须解决的问题。我花了几个小时试图解决这个问题,但一直没能解决。任何帮助将不胜感激。

问题

实现一个递归打印目录内容的方法ls() 以及所有的子目录,用缩进来表示有多深 在树结构中文件/目录是。

如果我们在前一个对象根上运行 ls(),它应该显示:

>> root.ls()
root
 boot.exe
 home
  thor
   hunde.jpg
   quatsch.txt
isaac
   gatos.jpg

到目前为止我的代码

class File:
    
    owner="default"

class Directory (File):
    
    
    def __init__(self,name,right):
        self.name=name
        self.right=right
    
    def chown (self,new_owner):
        self.new_owner=new_owner
        File.owner=new_owner
        
  
    
    def __str__(self):
        return "Directory({},{})".format(self.name,self.right)
    def __repr__(self):
        return "Directory({},{})".format(self.name,self.right)

#Method ls() which recursively prints the content of the directory and all the subdirectories


class PlainFile(File):
    
    
    def __init__(self,filename):
        self.filename=filename
    
    def chown (self,new_owner):
        self.new_owner=new_owner
        File.owner=new_owner
        
   
    def __str__ (self):
        return "PlainFile ({})".format (self.filename)
    
    
    def __repr__ (self):
        return "PlainFile ({})".format (self.filename)

    
print("Testing question 1")

# question 1 should allow to create simple files and folders:
file = PlainFile("boot.exe")
folder = Directory("Downloads",[])
    
root = Directory("root",[PlainFile("boot.exe"),
               Directory("home",[
                   Directory("thor",
                      [PlainFile("hunde.jpg"),
                       PlainFile("quatsch.txt")]),
                   Directory("isaac",
                      [PlainFile("gatos.jpg")])])])

print("-------------------------------------------------------------------------- \n")

#This is to test Question 2 
print(root)

print("-------------------------------------------------------------------------- \n")

#This is to test Question 3
file = PlainFile("boot.exe")
folder = Directory("Downloads",[])
print(f'file.owner: {file.owner}; folder: {folder.owner}')
file.chown("root")
folder.chown("isaac")
print(f'file.owner: {file.owner}; folder: {folder.owner}')

print("-------------------------------------------------------------------------- \n")

【问题讨论】:

  • 欢迎来到Stack Overflow. 请注意这不是代码编写或辅导服务。我们可以帮助解决具体的技术问题,而不是对代码或建议的开放式请求。请编辑您的问题以显示您需要帮助的具体问题。请参阅How To Ask a Good Question 页面,详细了解如何最好地帮助我们。

标签: python oop binary-tree


【解决方案1】:

你的函数应该给自己传递一个缩进(字符串),它会在每次递归调用时增加:

def ls(node,indent=""):
    print(indent + node.name)       # print indented name
    if isinstance(node,Directory):  # for directories
       for subNode in node.right:   # recursive calls for each item
           ls(subNode,indent+"  ")  # with increased indentation

如果您将此作为 File/Directory 类的方法,您可以使用 self 而不是 node 作为第一个参数,并专门化 Directory 类以使其打印其子节点:

# in the File class
def ls(self,indent=""):
    print(indent + self.name)    # print indented name

# in the Directory class
def ls(self,indent=""):
    super().ls(indent)           # from base class
    for subNode in self.right:   # recursive calls for each item
        subNode.ls(indent+"  ")  # with increased indentation

请注意,您的基类(文件)应将所有者设置为实例成员(在其 __init__() 方法中),子类应从 super() 调用基类的 __init__() 方法。这将允许每个文件/目录有一个特定的所有者。使用现在的代码,所有文件都只有一个所有者,因为 File.owner 是一个类变量

【讨论】:

  • 非常感谢您帮助我们。
猜你喜欢
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多