On Tue, 2012-01-10 at 10:50 +0800, 贾晓磊 wrote:
> in my views, if getattr(self, "_db", None) is not None: can be
> replaced to if hasattr(self,"_db"):
Actually that's not the same test at all. hasattr(self, "_db") will be
True even if self._db == None.
>>> class Foo (object):
... def __init__ (self):
... self.bar = None
>>> f = Foo ()
>>> hasattr (f, "bar")
Therefore you must have getattr (self, "_db") == None. Except perhaps
there is no attribute _db, which will throw an exception, so you must
have a default:
if getattr(self, "_db", None) is not None
And now you are back to the original code.