下面的类是 Anurag 的动态属性生成目录遍历器。
import os
class DirLister(object):
def __init__(self, root):
self.root = root
self._list = None
def __getattr__(self, name):
try:
var = super(DirLister).__getattr__(self, name)
return var
except AttributeError:
return DirLister(os.path.join(self.root, name))
def __str__(self):
self._load()
return str(self._list)
def _load(self):
"""
load once when needed
"""
if self._list is not None:
return
self._list = os.listdir(self.root) # list root someway
root = DirLister("/")
print root.etc.apache
有没有办法在上面的 Anurag 的 DirLister 中添加其他复杂的功能?所以当它到达一个文件 testdir/j/p 时,它会打印出文件 p 的第一行。
[IN] print testdir.j.p
[OUT] First Line of p
我制作了一个用于打印文件第一行的类:
class File:
def __init__(self, path):
"""Read the first line in desired path"""
self.path = path
f = open(path, 'r')
self.first_line = f.readline()
f.close()
def __repr__(self):
"""Display the first line"""
return self.first_line
只需要知道如何将它合并到下面的类中。谢谢你。