Skip to main content
 首页 » 编程设计

python之获取 Python 类中的变量类型

2025年05月04日21落叶无声

对于下面的例子,有没有办法获取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) 

请您参考如下方法:

您需要迭代值,但您正在迭代 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