检查Python中变量是否存在 - 与self不起作用
在你给这个帖子降分之前,我找不到其他地方有人问过这个问题。
我正在检查一个列表是否存在,使用的是
if 'self.locList' in locals():
print 'it exists'
但是它不管用。它总是认为这个列表不存在。这可能是因为我在使用继承,并且用 self.
在其他地方引用它,我不太明白发生了什么。
有人能帮我解释一下吗?
这是完整的代码:
import maya.cmds as cmds
class primWingS():
def __init__(self):
pass
def setupWing(self, *args):
pass
def createLocs(self, list):
for i in range(list):
if 'self.locList' in locals():
print 'it exists'
else:
self.locList = []
loc = cmds.spaceLocator(n = self.lName('dummyLocator' + str(i + 1) + '_LOC'))
self.locList.append(loc)
print self.locList
p = primWingS()
3 个回答
1
你可以使用try/except或者getattr配合默认值,但这些在你的代码中并不合适。__init__方法是用来初始化对象的:
def __init__(self):
self.locList = []
让locList不存在是没有意义的。一个长度为零的列表就是一个没有位置的对象。
11
从一个稍微不同的角度来回答这个问题。使用 Try ... catch
、getattr
或 dir
是如果你只是想让代码正常运行的好方法。
调用 locals()
会返回一个本地作用域的字典。这意味着它包含了 self
。不过,你想要的是 self
的一个子属性(self.locList
)。这个子属性根本不在字典里。你所做的事情最接近的方式是:
if 'locList' in dir(self):
print 'it exists'
函数 dir
是查询对象属性的通用方法。但正如其他帖子所提到的,从速度的角度来看,查询对象的属性并不是很有意义。
23
我觉得你想用的是 hasattr(self,'locList')
这个方法。
不过,通常来说,直接使用这个属性会更好,如果它不存在的话,程序会抛出一个 AttributeError
错误,你可以捕捉到这个错误:
try:
print self.locList
except AttributeError:
self.locList = "Initialized value"