简体   繁体   中英

Python class instance variables disappear

I define the response class like this:

class Response(object):
    def __index__(self):
        self.country = ""
        self.time_human = ""
        self.time_utc = ""
        self.text = ""
        self.time_object = None
        self.clean_word_list = []

    def parse_line(self, line):
        if 'text:' in line[:10]:
            self.text = line[7:].strip()
        elif 'country: ' in line[:9]:
            self.country = line[8:].strip()
        elif 'time_human: ' in line[:15]:
            self.time_human = line[12:].strip()
        elif 'time_utc: ' in line[:15]:
            self.time_utc = int(line[10:].strip())
            self.time_object = datetime.fromtimestamp(self.time_utc)

I then have a method that reads lines from a text file and assigns the proper value to the response:

class file_importer(object):
    def __init__(self, file_name):
        self.file_name = file_name

def get_responses_from_file(self):
    directory = DIRECTORY_TO_FILE
    formatted_filename = directory + self.file_name
    file = open(formatted_filename, 'r')
    response = Response()
    response_list = []
    for line in file:
        if line[0] == '*':
            response_list.append(response)
            response = Response()
        else:
            response.parse_line(line)
    return response_list

But the response_list that the get_responses_from_file() returns is a list of responses that do not have a response.clean_word_list attribute. What happened?

它必须是__init__而不是__index__在您的Response类中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM