python class variable works outside of class, not inside class

时间:2015-09-14 16:15:36

标签: python class

I have populated a couple of lists in my class. Outside of the class, I can print both lists. Inside the class, only one will show any elements. I don't see any spelling errors in my code, no syntax errors. I'm completely lost...

At the bottom, when running "logging.info(self.fcNetwork_List)", it returns empty. "logging.info(self.userName_list)" returns the list correctly.

#!/usr/bin/env python

import getopt, sys, os, errno 
import logging 
import getpass    
import requests
import json
from requests.auth import HTTPBasicAuth
import time
from restapi import *

class OV_enclosure(object):
    ip_address = ""
    api_version = ""
    OV_username = ""
    OV_password = ""
    auth = ""
    userName_list = []
    fcNetwork_list = []

    def __init__(self):
        pass

    def getAPIVersion(self):
        api_dict = getAPIVersion(self.ip_address)
        self.api_version = api_dict["currentVersion"]

    def getAuthID(self):
        auth_data = loginSessions(self.ip_address, self.api_version, self.OV_username, self.OV_password)

        try:
            self.auth = auth_data['sessionID']
        except KeyError:
            logging.error("Invalid key.  Verify your credentials in the loginSessions function")
            exit(1)

    def printClass(self):
        logging.debug("ip_address: %s" % self.ip_address)
        logging.debug("api_version: %s" % self.api_version)
        logging.debug("OV_username: %s" % self.OV_username)
        logging.debug("OV_password: %s" % self.OV_password)
        logging.debug("auth: %s" % self.auth)
        logging.debug("userName_list: %s" % self.userName_list)
        logging.info("self userName_List: ")
        logging.info(self.userName_list)
        logging.info("self fcNetwork_List: ")
        logging.info(self.fcNetwork_list)
        logging.debug("fcNetwork_list: %s" % self.fcNetwork_list)

Outside of class, both of these show a correctly populated list.

logging.info("printing enclosure username list")
logging.info(enclosure.userName_list)

logging.info("Printing enclosure fcNetworks list")
logging.info(enclosure.fcNetwork_List)


enclosure.printClass()
logging.info("Shutdown logging handles")
logging.shutdown()
print "\ndone"

I've excluded the code I feel is not important (entire class shown), but if you want all the code, I can do that.

1 个答案:

答案 0 :(得分:0)

我想这个问题是通过userName_list对象不正确地使用类变量self

如果实例变量self.userName_list不存在,getter将返回OV_enclosure.userName_list,但如果您在任何地方分配/定义实例版本,则阴影第一类。

您需要通过类名限定符显式访问类变量。