How to check if an object already called in Python?
I created an GUI using PyGTK.
I want to add, in some cases, more UI elements to my GUI. I did something like that:
try:
self.main.addServer(self.factory.logingo)
except:
self.main = MainWindow(self.factory.loginfo)
I want to call addServer when my object self.main (which is my gtk.Window object) already exist. But if it don't exist I want to call MainWindow which creates a开发者_JS百科 gtk.Window. My problem is, that my try never succeed and I always end in the except and recreate a self.main.
How to done that? Thanks in advance.
if not hasattr(self, 'main'):
self.main = MainWindow(self.factory.loginfo)
self.main.addServer(self.factory.logingo)
PS: be ware of try: ... except: ...
without any specific exceptation, unless when you know what are you doing. because that hides probable (and unexpected) exceptations. Instead, for example write:
try:
...
except AttributeError:
...
or anything that is expected and will be handled, instead of AttributeError
(for example, KeyError
or IndexError
or ImportError
or something)
And write as less code as possible in try block, for example you can write above code like this:
try:
self.main
except AttributeError:
self.main = MainWindow(self.factory.loginfo)
self.main.addServer(self.factory.logingo)
That is equivalent to that (its interesting to know that hasattr
itself uses a try except!), But using hasattr is cleaner and shorter here.
精彩评论