检查Python中是否存在变量 - 不适用于self

时间:2013-02-25 02:29:28

标签: python maya

在你回复这篇文章之前,没有人问过我能找到的任何内容。

我正在使用

检查是否存在列表
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 个答案:

答案 0 :(得分:12)

我想你想要hasattr(self,'locList')

尽管如此,你通常最好不要尝试使用属性并捕获AttributeError,如果它不存在则会被引发:

try:
    print self.locList
except AttributeError:
    self.locList = "Initialized value"

答案 1 :(得分:4)

从一个不同的角度回答。如果您只是希望代码能够正常运行,Try ... catchgetattrdir就可以了。

调用locals()返回本地范围的字典。这包括self。但是,您要求selfself.locList)的孩子。孩子根本就不在字典里。与你正在做的最接近的事情是:

if 'locList' in dir(self):
    print 'it exists'

函数dir是查询对象项的通用方法。但正如其他帖子所述,从速度角度查询对象的属性没有多大意义。

答案 2 :(得分:1)

您可以使用带有默认值的try / except或getattr,但这些内容对您的代码没有意义。 __init__方法用于初始化对象:

def __init__(self):
    self.locList = []

允许locList不存在是没有意义的。零长度列表是没有位置的对象。