对于下面的示例,是否可以将a
和b
的类型作为int
和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)
答案 0 :(得分:4)
您需要迭代这些值,但是您正在迭代vars(test_obj)
的键,当这样做时,它可以工作。
还可以使用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__)
输出将为
int
str
答案 1 :(得分: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)
您也访问attr
,这将返回a
和b
。 value
将返回变量的值。
答案 2 :(得分:0)
一个示例还打印类型:
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)))
将提供:
{'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'>