AttributeError:添加新类变量时,对象没有属性

时间:2015-09-27 18:52:39

标签: attributeerror

我有以下CODE(片段)......它可能对其他人有用......但我有一个问题...我的一个类变量似乎不起作用,好像数量有限您可以使用哪些变量?

    import csv

    class MASAT_data:
    #
    #  ALL CSV files are expected to have the first row as headers
    #  ALL CSV files are expected to have the first column as the key attribute
    #  All Headers are extracted into its own object variable
    #

    def __init__(self, fname, action, intest):
        __data_Dict = {}
        __fname = fname
        __header = []             # <--- THIS WORKS
        __colLEN = 0
        __rowLEN = 0
        __data_rows = []          # <--- This seems to not be available to the class
        #__test = intest
        if action.upper == "NEW":
            pass
        else:
            self.Get_DICT(__fname)
    def Get_DICT(self,filename):
        templist = []
        daDict = {}
        with open(filename,"r") as f:
            csv_f = csv.reader(f)
            x=-1
            for row in csv_f:
                x+=1
                if len(row)!=0:
                    if x == 0:
                        self.__header = row
                        self.__colLEN = len(self.__header)
                    else:
                        templist = row
                        self.__data_rows.append(templist)   # <-- line 38
                        if len(templist) >= 2:
                            daDict[templist[0]] = templist[1:]
        self.__rowLEN = x
        f.close()
        self.__data_Dict = daDict
    def rtnData(self,keyName):
        return self.__data_Dict[keyName]
    def hlen(self):
        return self.__colLEN
    def __len__(self):
        return self.__rowLEN
    def rtnList(self):
        templist = [[]]
        temps = []
        for key, value in self.__data_Dict.items():
            temps.append(key)
            for x in value:
                temps.append(x)
            templist.append(temps)
            temps = []
        templist.pop(0)


        #for x in range(len(templist)):
        #    print(templist[int(x)])
        return templist
    def rtnListDict(self):
        templist = []
        for x in range(len(self.__header)):
            print (self.__header[x])
            #print (self.__data_Dict[self.__header[x]])

我收到以下错误:

C:\Python34\python.exe C:/Users/User/PycharmProjects/MASAT-3/MA-SAT_v3_MAIN.py
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/MASAT-3/MA-SAT_v3_MAIN.py", line 10, in <module>
    appCONFIGs = MASAT_data("CONFIG.csv","LOAD",t)
  File "C:\Users\User\PycharmProjects\MASAT-3\MASAT_Libs.py", line 23, in __init__
    self.Get_DICT(__fname)
  File "C:\Users\User\PycharmProjects\MASAT-3\MASAT_Libs.py", line 38, in Get_DICT
    self.__data_rows.append(templist)
AttributeError: 'MASAT_data' object has no attribute '_MASAT_data__data_rows'

使用退出代码1完成处理

调用程序如下:

    __author__ = 'User'
    import sys
    from MASAT_Libs import *

    sys.path.append('C:\\Users\\User\\PycharmProjects\MASAT-3')
    t = 0
    #define Globals

    if __name__ == '__main__':
        appCONFIGs = MASAT_data("CONFIG.csv","LOAD",t)
        if appCONFIGs.rtnData("ApplicationMode")[0] == 'DEBUG':
            t = 1
        else:
            t = 0
        print("t = ",t)
        observations = MASAT_data(appCONFIGs.rtnData("PathName")[0] + "\\Observables.csv", "LOAD",t)
        KMNs = MASAT_data(appCONFIGs.rtnData("PathName")[0] + "\\KMN_List.csv", "LOAD",t)
        geomix = MASAT_data(appCONFIGs.rtnData("PathName")[0] + "\\geomix_perf_list.csv", "LOAD",t)

        print (geomix.rtnList())
        print (len(geomix))

        geomix.rtnListDict()

所以请原谅我,如果我放入一个额外的空间,或者没有正确缩进(我在这里处理代码时手动完成...

我的问题是,我不能在这个类中添加另一个变量(无论名称是什么),而不会以这种方式进行操作。有任何简单修复的想法吗?

2 个答案:

答案 0 :(得分:0)

声明实例变量的正确方法是:

Thread t = new Thread(new ThreadStart(DoPointsShift));
t.Start();

private void DoPointsShift()
        {
            int turnsPerMinute = 5;
            long delay = 60 / turnsPerMinute * 1000 / (360 / 2);
            long deltaDelay = delay;

        int beginTime = Environment.TickCount;
        EasingFunctionBase ease = new CircleEase();
        ease.EasingMode = EasingMode.EaseInOut;
        while (true)
        {
            TimeSpan duration = TimeSpan.FromSeconds(1 - 1 * rnd.NextDouble());
            foreach (var p in points)
            {
                var x = p.OriginX - 50 + rnd.NextDouble() * 100;
                var y = p.OriginY - 50 + rnd.NextDouble() * 100;
                PointAnimation anim = new PointAnimation(new Point(x, y), duration);
                anim.EasingFunction = ease;
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    p.BeginAnimation(ParallaxPoint.PointCoordProperty, anim); //exception here
                }));
            }
            while (Environment.TickCount - beginTime < delay) { }
            delay += deltaDelay;
        }
    }

class MASAT_data: def __init__(self, some_var): # like this self.__header = [] self.__data_rows = [] self.__some_var = some_var def some_func(self): # and referenced like this self.__header.append(['test']) self.__data_rows.append(['test']) print(self.__some_var) 中声明变量时,其范围仅限于__init__。因此,如果您需要在别处引用它,它必须具有更大的范围。因此__init__

答案 1 :(得分:0)

好吧这似乎有用了我玩了一下......所有我真正需要做的就是把self.放在所有变量的前面......不确定为什么但这似乎需要?如果有人知道为什么会这样,我很想知道技术原因...

def __init__(self, fname, action, intest):
    self.__data_Dict = {}
    self.__fname = fname
    self.__header = []             # <--- THIS WORKS
    self.__colLEN = 0
    self.__rowLEN = 0
    self.__data_rows = []          # <--- This seems to not be available to the class
    #__test = intest
    if action.upper == "NEW":
        pass
    else:
        self.Get_DICT(self.__fname)