I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr
like this:
class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
But you can also do this:
class Foo(object):
@classmethod
def singleton(self):
try:
return self.instance
except AttributeError:
self.instance = Foo()
return self.instance
Is one method better of the other?
Edit: Added the @classmethod
... But note that the question is not about how to make a singleton but how to check the presence of a member in an object.
Edit: For that example, a typical usage would be:
s = Foo.singleton()
Then s
is an object of type Foo
, the same each time. And, typically, the method is called many times.