I have came across the function vars()
in python i know it returns __dict__
attribute of the object passed to the function But can you give me a real world usage example like where we can use it in real project
Asked
Active
Viewed 76 times
0
-
1... whenever you want access to `__dict__`, no? – juanpa.arrivillaga Jan 21 '19 at 02:03
-
I don't think it is a good practice, but sometimes it is useful when you don't want to pass all the variables when formatting string https://stackoverflow.com/questions/2201867/capturing-vars-pattern-in-string-formatting – ymonad Jan 21 '19 at 02:51
1 Answers
1
Let me take an example: sometimes you may need check a class object's attribute is None or others, you can use the vars()
class Test(object):
def __init__(self):
self.a = None
self.b = None
self.c = None
def init_abc(self, init_dict):
"""init class param"""
self.a = init_dict.get('a')
self.b = init_dict.get('b')
self.c = init_dict.get('c')
def __repr__(self):
return 'a=%s,b=%s, c=%s' % (self.a, self.b, self.c)
test = Test()
init_abc_dict = {'a':1, 'c':2}
test.init_abc(init_abc_dict)
print 'Test:%s' % test
if None in vars(test).values():
print 'some attr is None'

NullE
- 11
- 2