类没有属性,即使使用self作为参数Python也是如此

2024-05-14 00:53:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下Python类:

import sys
import re

class Parser:

    def __init__(self, filename=""):
        self.filename = filename

    def parse(self):

        try:
            table = {}
            fp = open(self.filename, 'r')
            records = fp.readlines()
            for record in records:
                (index, column, value) = record.strip().split()
                value = value[:3]
                table[column] = value

            return table

        except IOError:
            print "Could not open file ", self.filename
            sys.exit(1) 

    def organize_map(self, table={}):

        new_table = {
            'profile_1': [],
            'profile_2': [],
            'profile_3': [],
            'profile_4': []
        }

        for k, v in table.iteritems():

            if re.match("profile1", k):
                new_table['profile_1'].append(int(v))
            elif re.match("profile2", k):
                new_table['profile_2'].append(int(v))
            elif re.match("profile3", k):
                new_table['profile_3'].append(int(v))
            elif re.match("profile4", k):
                new_table['profile_4'].append(int(v)) 


        for k, v in new_table.iteritems():
            v.sort()
            v = v[2:len(v)-2]
            new_table[k] = v
            new_table[k].append(avg(v))
            new_table[k].append(std(v))

        return new_table

parser = Parser()
table = parser.parse()
print parser.organize_map(table)

当我执行parser.py文件时,我得到:

  File "parser.py", line 94, in <module>
    print parser.organize_map(table)
AttributeError: Parser instance has no attribute 'organize_map'

我不知道为什么。。。我用self关键字定义了organized_map()。。。你知道吗? 示例文件:

1: profile1_test_1 155700802.32
2: profile1_test_2 156129130.88
3: profile1_test_3 155961744.64
4: profile1_test_4 155917583.6
5: profile1_test_5 156193748.16
6: profile1_test_6 155749778.88
7: profile1_test_7 156040104.72
8: profile1_test_8 156934277.68
9: profile1_test_9 156976866.56

Tags: intestselfreparsermapnewvalue
1条回答
网友
1楼 · 发布于 2024-05-14 00:53:50

如果在源代码中将缩进与制表符和空格混合在一起,那么python解释器对制表符的解释可能与您预期的不同。organize_map的定义是用制表符缩进的,很可能它最终被看作是parse内部的一个局部函数。你知道吗

不要把缩进与制表符和空格混在一起,这只会导致混淆。运行脚本时,还可以使用Python的-t参数获取有关不一致缩进的警告:

python -t myscript.py

相关问题 更多 >