I'm trying to verify if a python object has an attribute inside the definition of one of its methods, here is some code to clarify :
class A :
def __init__(self) :
self.__a = 5
def hasAttr(self) :
if hasattr(self, '__a'):
print(True)
else :
print(False)
If I execute the code
x = A()
x.hasAttr()
I get False, I know the reason it doesn't work is that the attribute is virtually private, but I'm not intending to access the attributes outside of the class, I just want to verify if the attribute has been yet definded , I know I can always use :
class A :
def __init__(self) :
self.__a = 5
def hasAttr(self) :
if ('_'+self.__class__.__name__ + '__a') in self.__dict__:
print(True)
else :
print(False)
But isn't there a more soft way to do it ?