python - How to check if a class member exists without getting exception -


for primitive types can use if in : boolean check. if use in syntax check existence of class member nameerror exception. there way in python check without exception? or way surround in try except block?

here sample code.

class myclass:     = 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' not defined if counter in x:     print "counter in x" else:     print "no counter in x" 

the error because using counter (a name) , not 'counter' (the string). however, if use 'counter' not expect, typeerror: argument of type 'a' not iterable - cannot iterate on custom object.

instead, use __dict__ attribute of instance:

>>> class a(object): ...     = 0 ...     def __init__(self, num): ...         self.i = num ... >>> x = a(3) >>> x.i 3 >>> 'i' in x.__dict__ true >>> 'counter' in x.__dict__ false 

or more appropriate hasattr jon pointed out.

>>> hasattr(x, 'counter') false >>> hasattr(x, 'i') true 

Comments