プリミティブ型の場合、if in : boolean チェックを使用できます。しかし、in 構文を使用してクラス メンバの存在を確認すると、NameError 例外が発生します。Pythonで例外なくチェックする方法はありますか? それとも、ブロックを除いてtryで囲む唯一の方法ですか?
これが私のサンプルコードです。
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"