简体   繁体   中英

Instance attributes in Python and __init__ method

I am trying to writing a program to read a configuration file but while testing it am having this error:

self.connection_attempts = self.config_file.get('CONNECTION_ATTEMPTS', 'TIME')
AttributeError: 'list' object has no attribute 'get'

I ma pretty sure it is something I don't get, but it is few hours I am trying to understand where the problem is. My __init__ method looks like this:

import simpleconfigparser

class ReportGenerator:
    def __init__(self):
        self.config_parser = simpleconfigparser.configparser()
        self.config_file = config_parser.read('config.ini')
        self.connection_attempts = config_file.get('CONNECTION_ATTEMPTS', 'TIME')
        self.connection_timeout = config_file.get('CONNECTION_TIMEOUT', 'TIMEOUT')
        self.report_destination_path = config_file.get('REPORT', 'REPORT_PATH')

This code uses the SimpleConfigParser package.

You want config_parser.get() not config_file.get() . config_parser.read() simply returns the list of config files successfully read after populating the config object. (Usually it is called config or cfg , not config_parser ).

This list ( config_file ) serves no purpose in your code and you might as well not capture it at all.

from simpleconfigparser import simpleconfigparser

TIME = 5
TIMEOUT = 10
REPORT_PATH = '/tmp/'

class ReportGenerator:
    def __init__(self):
        self.config = simpleconfigparser()
        config.read('config.ini')

        self.connection_attempts = config.get('CONNECTION_ATTEMPTS', TIME)
        self.connection_timeout = config.get('CONNECTION_TIMEOUT', TIMEOUT)
        self.report_destination_path = config.get('REPORT', REPORT_PATH)

My guess would also be, that you use the default value in .get() the wrong way, but i cannot be certain with the information you have given.

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