无法访问类对象的__getitem__

时间:2013-09-04 20:45:46

标签: python metaprogramming super magic-methods

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

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

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

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

我怀疑你想要设置一个属性;如果是这样,请在setattr()上使用self

setattr(self, FileName_withoutExtension, OS_appropriete_file(self.root,fileName))

答案 1 :(得分:0)

您似乎必须在__setitem__中实施方法dirClass,然后才能在create_file中使用它。 __setitem__方法是一个抽象方法/接口,每个使用它的类都必须实现它。

This reference可能相关。