简体   繁体   中英

access class variables inside a function in python

I am trying to read some values from a config file in python inside a class and then i am trying to access these variables inside one more function inside the same class. I have tried the below code but there seems to be something wrong in my code. Here is what i tried:

class CLEAN():
    def __init__(self):
        parser = argparse.ArgumentParser(description='Remove inactive users from artifactory')
        parser.add_argument('-f', '--config_file', dest='config_file', default="", required=True, action="store", help='the config file with creds')
        parser.add_argument('-d', '--log_dir', dest='log_dir', default="", required=True, action="store", help='the logs dir')
        parsers = parser.parse_args()

        self.config_file = parsers.config_file.strip()
        self.log_dir = parsers.log_dir.strip()

        if not os.path.exists(self.log_dir):
            os.mkdir(self.log_dir)

        with open('config.ini', 'r') as myfile:
            for line in myfile:
                if 'instance' in line:
                     instance = line.split('=')[1]
                if 'user' in line:
                    user = line.split('=')[1]
                if 'user_api' in line:
                     user_api = line.split('=')[1]

    def print_values(self):
        logger.info(self.instance)
        logger.info(self.user)
        logger.info(self.user_api)`

This part of the code is followed by main() The error that i am getting is

Traceback (most recent call last):
 File "clean.py", line 48, in <module>
    c.main()
  File "clean.py", line 44, in main
    self.print_values()
  File "clean.py", line 39, in print_values
   logger.info(self.instance)
AttributeError: CLEAN instance has no attribute 
'instance'


cat config.ini
instance=xxxxx
user=abc
user_api=xxxx

You need to add self. :

self.instance = line.split('=')[1]

Same for user and user_api .

On the flip side, you don't need self for config_file or log_dir if you're not going to use those variables outside of that method.

As bruno says, using ConfigParser:

from configparser import ConfigParser

config = ConfigParser()
config.read('config.ini')
print(config['section']['instance'])  # xxxxx

This requires adding a line [section] to the top of the config file. Any title will do, but a section header is required.

Then you can you self.config = config['section'] and access the values as self.config['instance'] .

Here:

     with open('config.ini', 'r') as myfile:
        for line in myfile:
            if 'instance' in line:
                 instance = line.split('=')[1]
            if 'user' in line:
                user = line.split('=')[1]
            if 'user_api' in line:
                 user_api = line.split('=')[1]

You are creating local variables, not instance attributes. You have to assign to self.instance , self.user and self.user_api` instead.

Also, with your current code, there's no garantee that those attributes will be set (if the "user", "user_api" or "instance" words are not found in the file), so you want to first set those attributes to default values, ie:

     # which default value makes sense is up to you
     self.instance = None
     self.user = None
     self.user_api = None

     with open('config.ini', 'r') as myfile:
        for line in myfile:
            if 'instance' in line:
                 self.instance = line.split('=')[1]
            if 'user' in line:
                self.user = line.split('=')[1]
            if 'user_api' in line:
                 self.user_api = line.split('=')[1]

Also, python has a ConfigParser class that knows how to deal with ini files, so you'd probably be better using this instead.

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