Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class member exists without getting exception

Tags:

python

For primitive types I can use the if in : boolean check. But if I use the in syntax to check for the existence of a class member I get a NameError exception. Is there a way in Python to check without an exception? Or is the only way to surround in try except block?

Here is my sample code.

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"
like image 359
Angus Comber Avatar asked Jul 11 '13 10:07

Angus Comber


People also ask

What is Python attribute?

Python class attributes are variables of a class that are shared between all of its instances. They differ from instance attributes in that instance attributes are owned by one specific instance of the class only, and are not shared between instances.


1 Answers

You can use hasattr

if hasattr(x, 'counter'):
    # whatever
like image 94
Jon Clements Avatar answered Nov 07 '22 22:11

Jon Clements