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

Vii*_*Vii 3 python maya

在你回复这篇文章之前,没有人问过我能找到的任何帖子.

我正在检查是否存在列表

if 'self.locList' in locals():
    print 'it exists'
Run Code Online (Sandbox Code Playgroud)

但它不起作用.它从未认为它存在.这一定是因为我正在使用继承而在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()
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 12

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

虽然,通常情况下,尝试使用属性并捕获AttributeError哪个属性(如果不存在)会更好:

try:
    print self.locList
except AttributeError:
    self.locList = "Initialized value"
Run Code Online (Sandbox Code Playgroud)

  • +1:对于[Python EAFP成语](http://docs.python.org/2/glossary.html#term-eafp). (2认同)

joo*_*jaa 8

换个角度回答一下。Try ... catchgetattr或者dir如果您只是想让代码正常工作,则是要走的路。

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

if 'locList' in dir(self):
    print 'it exists'
Run Code Online (Sandbox Code Playgroud)

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