在Python类中获取变量类型

时间:2019-05-08 17:11:29

标签: python class

对于下面的示例,是否可以将ab的类型作为intstring获得?

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)

3 个答案:

答案 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,这将返回abvalue将返回变量的值。

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