python serval variables combine into a dict? – Education Career Blog

All,

A class:

class foo():
    def __init__(self):
        self.avar1 = 0
        self.bvar2 = 1
        self.cvar3 = 3
    def debug_info(self):
        print "avar1:" avar1
        print "bvar2:" bvar2
        print "cvar3:" cvar3

my question, it is too complex to write the debug_info() if I got a lot of self.vars
,then I want to migrate them into a dict to print them in one go for debug and monitor purpose, however, maybe I do not want to lost the format

foo.avar1 = 0

to access the vars inside of the class, because it is easy to read and easy to use and modify. Do you have better idea instead of visit the class.dict for the debug_info output? or does someone knows a better way to make this class more simple?

Thanks!

,

def debug_info ( self ):
    for ( key, value ) in self.__dict__.items():
        print( key, '=', value )

,

Every Python object already has such a dictionary it is the self.__dict__ This prints reasonably well like and other Python dict, but you could control the format using the Data pretty printer in the Python standard library of looping through the elements in the dictionary and printing them however you want as shown below:

class foo():
    def __init__(self):
        self.avar1 = 0
        self.bvar2 = 1
        self.cvar3 = 3
    def debug_info(self):
        for k in self.__dict__:
            print k + ':' + str(self.__dict__k)


>>> foo().debug_info()
bvar2:1
cvar3:3
avar1:0

,

Modules, Classes and Instances all have __dict__ so you can reference it on the instance you wish to display the debug for:

>>> f = foo()
>>> f.__dict__
{'bvar2': 1, 'cvar3': 3, 'avar1': 0}

,

While using __dict__ will work in most cases, it won’t always work – specifically for objects that have a __slots__ variable.

Instead, try the following:

vars = var for var in dir(obj) if not callable(getattr(obj, var)) and not var.startswith('__')

,

Others have answered your question about printing. If you have a lot of variables to set in your __init__ method, you can also use __dict__ to make that a little shorter. If you have a lot of variables, this will at least keep you from having to type self all the time. I think the standard way is more readable in most cases, but your mileage may vary.

def __init__(self):
    vars = dict(avar1=0, bvar2=1, cvar3=3)
    self.__dict__.update(vars)

Leave a Comment