對於基本類型,我可以使用if in:布爾檢查。但是如果我使用in語法來檢查類成員的存在,我會得到一個NameError異常。有沒有一種方法在Python中檢查沒有異常?或者是嘗試除了塊以外的唯一方法?如何檢查類成員是否存在,但沒有得到異常
這是我的示例代碼。
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"
的複製http://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists-in-python – Regenschein
@fordprefect雖然它可能是重複的,但它不是該問題的重複。這是關於對象屬性的,這個問題是關於局部和全局變量的。 – delnan