如何创建一个为两者创建目录的类,包括1.初始值和2.输入参数?
这是我的代码mypath.py
import os
myroot = 'D:\\pet'
class path(object)
dog = os.path.join(myroot, 'dog')
cat = os.path.join(myroot, 'cat')
# my 1st question (something like this)
def __init__(self):
for directory in dir(self):
if not os.path.exists(directory):
os.makedirs(directory)
# my 2nd question (something like this)
def append(self, newpath)
for directory in dir(self):
newdir = os.path.join(directory, newpath)
if not os.path.exists(newdir):
os.makedirs(newdir)
# update attribute in self
self.directory = newdir
当我这样做时
import mypath
我可以看到
mypath.dog = 'D:\\pet\\dog'
mypath.cat = 'D:\\pet\\cat'
但它们不是创建的,而是我手动必须这样做:
os.mkdir(mypath.dog)
os.mkdir(mypath.cat)
所以我的问题#1是
如何在导入时让类自动创建每个路径?
和问题#2是
如何创建子函数.append()以便
mypath.append('ishungry')
自动更新路径中的所有属性,以便
mypath.dog = 'D:\\pet\\dog\\ishungry'
mypath.cat = 'D:\\pet\\cat\\ishungry'
提前致谢!
答案 0 :(得分:1)
所以逻辑使目录存在于对象__init__方法中;这不会在导入时运行。这就是为什么在导入模块时,不会创建目录。要制作它们,您必须创建“路径”对象的实例:
import mypath
my_path= mypath.path()
是否有令人信服的理由在导入时而不是在对象初始化时创建这些目录?通常认为code smell对模块导入具有此类副作用。
更简洁的方法可能是让一个对象为你处理所有路径的东西,并直接使用该对象:
class PathManager(object):
"""Manages file system paths
:param root: The base of all paths
:type root: String
:param top_dirs: The frist class directories we care about.
:type top_dirs: List
"""
def __init__(self, root='D:\\pet', top_dirs=None)
self.root = root
self.top_dirs = [] if top_dirs is None else top_dirs
self._config_dir()
def _config_dir(self, new_dir=None)
"""Updates all managed paths to contain new_dir"""
for folder in self.top_dirs:
if new_dir is not None:
directory = os.path.join(self.root, folder, new_dir)
else:
directory = os.path.join(self.root, folder)
if not os.path.exists(directory):
os.makedirs(directory)
def append(self, new_dir):
"""Add a new subdirectory to all managed paths, then update
the list of managed paths"""
# add new paths to file system
self._config_dir(new_dir=new_dir)
# update class to know of update managed paths
self.top_dirs = [os.path.join(self.root, x, new_dir) for x in self.top_dir]
然后使用它:
from mypath import PathManager
# Creates the initial paths
path_mgr = PathManager(top_dirs=['dog, 'cat'])
# add a new subdir to managed path
path_mgr.append('ishungry')
答案 1 :(得分:1)
试试这个:
注意:根据操作系统更改斜杠'\'或'/'
mainxD.py
import os
class pathmy(object):
currentfolder = os.path.dirname(os.path.realpath(__file__)) # get your current folder
folders = [currentfolder+'/dog', currentfolder+'/cat']
# my 1st question (something like this)
def __init__(self):
for x in self.folders:
if not os.path.exists(x):
os.makedirs(x)
# my 2nd question (something like this)
@classmethod
def addthis(self, newpath):
newfolder = [x+'/'+newpath for x in self.folders]
# update attribute in self
for x in newfolder:
if not os.path.exists(x):
os.makedirs(x)
print 'Okay'
if not __name__ == '__main__':
pathmy()
other.py
from mainxD import pathmy
print pathmy.folders
print pathmy.addthis('newfolder')