1

For the following example, is there a way to get the type of a and b as int and string?

class test(object):
    def __init__(self):
        self.a = 1
        self.b = "abc"

test_obj = test()
for var in vars(test_obj):
     print type(var) # this just returns string type as expected (see explanation below)
prosti
  • 42,291
  • 14
  • 186
  • 151
Zack
  • 1,205
  • 2
  • 14
  • 38

3 Answers3

4

You need to iterate on the values, but you are iterating on the keys of vars(test_obj), when you do that, it works.

Also you can get the name of object using value.__class__.__name__

class test(object):
    def __init__(self):
        self.a = 1
        self.b = "abc"

test_obj = test()

print(vars(test_obj))
#Iterate on values
for value in vars(test_obj).values():
    #Get name of object
    print(value.__class__.__name__) 

The output will be

int
str
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
1
class test(object):
    def __init__(self):
        self.a = 1
        self.b = "abc"

test_obj = test()

for attr, value in test_obj.__dict__.iteritems():
    print type(value)

You access the attr as well which will return a and b. value will return the values of the variables.

Aditya Patel
  • 148
  • 1
  • 1
  • 11
0

One example also printing the type:

class test(object):
    def __init__(self):
        self.a = 1
        self.b = "abc"

test_obj = test()

print(vars(test_obj))

# print(dir(test_obj))

#Iterate on values
for k, v in vars(test_obj).items():
    print('variable is {0}: and variable value is {1}, of type {2}'.format(k,v, type(v)))

Will provide:

{'a': 1, 'b': 'abc'}
variable is a: and variable value is 1, of type <class 'int'>
variable is b: and variable value is abc, of type <class 'str'>
prosti
  • 42,291
  • 14
  • 186
  • 151