Skip to main content
 首页 » 编程设计

python之如何检查类成员是否存在而不会出现异常

2025年05月04日11qq号

对于原始类型,我可以使用 if in : bool 检查。但是如果我使用 in 语法检查类成员是否存在,我会得到一个 NameError 异常。 Python中有没有一种方法可以检查无异常?还是在 try except block 中包围的唯一方法?

这是我的示例代码。

class myclass: 
    i = 0 
    def __init__(self, num): 
        self.i = num 
 
mylist = [1,2,3] 
if 7 in mylist: 
    print "found it" 
else: 
    print "7 not present"  #prints 7 not present 
 
 
x = myclass(3) 
print x.i       #prints 3 
 
#below line NameError: name 'counter' is not defined 
if counter in x: 
    print "counter in x" 
else: 
    print "No counter in x" 

请您参考如下方法:

您可以使用 hasattr

if hasattr(x, 'counter'): 
    # whatever