我在动态创建类实例成员时遇到问题。我正在尝试创建一个行为类似于目录的类对象,并且具有以类中包含的文件命名的实例成员。
但是,我无法达到__setitem__()
该课程的方法。我可能正在接近这个错误。我不知道。
这是我的代码:
import IPython
import sys, os
ipath = IPython.utils.path.get_ipython_dir()
tutorial_config = "%s/profile_peter/startup"%ipath
sys.path.append(tutorial_config)
from tutorial_helpers import directoryClass, fileClass
## Determine Operating System
if sys.platform == "win32":
OperatingSystem = "Windows"
elif sys.platform =="linux2":
OperatingSystem = "Linux"
else:
raise Exception("could not find OS")
print OperatingSystem
root_path = os.getcwd()
class OS_appropriete_file():
separator = None
def __init__(self, rootPath, relative_path):
self.create_separator(relative_path)
self = fileClass(rootPath+self.separator+relative_path)
def create_separator(self,relative_path):
if OperatingSystem == "Windows":
escape_sequences = ['a','b','f','t','v','n','r','x']
self.separator = "\\"
elif OperatingSystem == "Linux":
self.separator = "/"
class dirClass(object):
def __init__( self,root,newFileName):
separator = self.create_separator(newFileName)
self.root = root+separator+newFileName
def create_file(self,fileName):
FileName_withoutExtension = fileName.split(".")[0]
print "extless:"
print FileName_withoutExtension
super(dirClass,self).__setitem__(FileName_withoutExtension, OS_appropriete_file(self.root,fileName))
#self.__class__.__dict__[FileName_withoutExtension] = OS_appropriete_file(self.root,fileName)
def create_separator(self,relative_path):
if OperatingSystem == "Windows":
escape_sequences = ['a','b','f','t','v','n','r','x']
separator = "\\"
elif OperatingSystem == "Linux":
separator = "/"
return separator
class files():
mypackage=dirClass(root_path,"mypackage")
mypackage.create_file("__init__.py")
mypackage.create_file("main.py")
## subpackage
subpackage1=dirClass(root_path,"subpackage1")
subpackage1.create_file("sub1.py")
subpackage1.create_file("__init__.py")
subpackage2=dirClass(root_path,"subpackage2")
subpackage2.create_file("sub2.py")
subpackage2.create_file("__init__.py")
if __name__ == "__main__":
fileEx = files()
当我使用导入此文件时from referenced_paths_and_files import *
,出现错误:
AttributeError: 'super' object has no attribute '__setitem__'
我要做的是创建一个 dirClass 实例,该实例具有一个以参数“newFileName”命名的成员变量,该参数是 OS_appropriete_file 的一个实例。
非常感谢您的帮助!