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"
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.
You can use hasattr
if hasattr(x, 'counter'):
# whatever
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With