0

我在动态创建类实例成员时遇到问题。我正在尝试创建一个行为类似于目录的类对象,并且具有以类中包含的文件命名的实例成员。

但是,我无法达到__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 的一个实例。

非常感谢您的帮助!

4

2 回答 2

1

object没有方法_ _ 它不是支持索引的类型。只有可变序列和映射对象实现。该方法通常用于挂钩索引分配 ( )。__setitem____setitem__obj[key] = value

我怀疑您想设置一个属性;如果是这样,只需setattr()使用self

setattr(self, FileName_withoutExtension, OS_appropriete_file(self.root,fileName))
于 2013-09-04T20:49:45.630 回答
0

看来您必须先实现 in 中的方法__setitem__dirClass然后才能在create_file. 该__setitem__方法是一个抽象方法/接口,每个使用它的类都必须实现它。

这个参考可能是相关的。

于 2013-09-04T20:55:26.607 回答