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)
4
  • 1
    "this just returns string type as expected" Why is this expected? Commented May 8, 2019 at 17:15
  • type(var).__name__ Commented May 8, 2019 at 17:16
  • 1
    vars(test_obj) is a dictionary and so var is just the variable names 'a' and 'b'. Commented May 8, 2019 at 17:17
  • print(type(getattr(test_obj, var))) Commented May 8, 2019 at 17:17

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

I think he wants the string 'int', not the object <class 'int'>
Updated, Thanks @Barmar :)
No worries! People make mistakes :) Glad to help @Lemon ! If the answer helped you, please consider accepting it by clicking the tick next to it :) Please also consider taking a look at stackoverflow.com/help/someone-answers :)
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.

Comments

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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.