【发布时间】: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