How to check if instance exists if variable not existing?

妖精的绣舞 提交于 2019-12-13 00:29:16

问题


I have a button which imports a module with a class. The class (varClass) creates a window.

If i click the button once again, i try this:

if var:
    var.toggleUI()
else :
    var = varClass()

But var doesn' exist the first time you create the window after opening Maya. How can i get this working?


回答1:


You could catch the NameError exception:

try:
    var.toggleUI()
except NameError:
    var = varClass()

If you needed call toggleUI the first time too, just try the name itself:

try:
    var
except NameError:
    var = varClass()

var.toggleUI()

I'm not familiar with Maja, but if you can define the name elsewhere first and simply set it to None there, then your code would work too, if not better.




回答2:


Use Exceptions:

try:
    var.toggleUI()
except NameError:
    var = varClass()
    var.toggleUI()



回答3:


You could use the dir function

a=5
'a' in dir()
'b' in dir()

This will print

True
False

So in your case

if 'var' in dir():
    var.toggleUI()
else :
    var = varClass()



回答4:


If you're doing this inside a button, you should offload the management of the var to the the module you're importing. Let the module handle the instantiation and the button lets the module do the heavy lifting. Rendundant imports dont hurt as long as the import has no side-effects (which it should not have if you're doing it right).

The module does something like this:

class SampleGui(object):
     # all sorts of good stuff here

_sample_gui_instance = None
def get_instance():
    _sample_gui_instance = sample_gui_instance or SampleGui()
    return _sample_gui_instance 

and the button just does

import SampleGuiModule
SampleGuiModule.get_instance().toggleUI()

This is the same check as the ones in everybody else's answer, but I think by delegating instance management to the module, instead of the button, you can have any level of complexity or initialization going on and share it between buttons, hotkeys or other scripts transparently.

I saved a few characters by using the or instead of if... is None; this will be tricky of for some reason a SampleGui truth tests as false. But it will only do that if you make force it to.

possibly useful: maya callbacks cheat sheet




回答5:


Default your var, and use it as a test:

var = None
if var is None:
  var = varClass()
var.toggleUI()


来源:https://stackoverflow.com/questions/28624679/how-to-check-if-instance-exists-if-variable-not-existing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!