以下のクラスは、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
以下のクラスに組み込む方法を知っておく必要があります。ありがとうございました。