2013-02-25 52 views
2

在你写下这篇文章之前,并没有问过我能找到的任何地方。检查一个变量是否存在于Python中 - 不适用于自己

我用

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() 
+1

你能检查你的代码的缩进吗?我想我可以告诉它应该如何,但很难说。 – Marius 2013-02-25 02:31:15

+2

为什么不在'__init__'里面创建它,而不是每次都检查? – wim 2013-02-25 02:32:27

回答

10

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

虽然,你平时最好尝试使用属性和追赶它被提出的AttributeError如果它不是” t目前:

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

+1:[Python EAFP idiom](http://docs.python.org/2/glossary.html#term-eafp)。 – Johnsyweb 2013-02-25 02:33:09

+0

@Johnsyweb - 是的,从性能的观点来看,'try' -'except'几乎肯定会击败'hasattr',因为docs明确声明'hasattr'是通过尝试'getattr'来实现的,并且检查异常... – mgilson 2013-02-25 02:47:17

1

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

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

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

+0

把它放在init中是行不通的,它根本不知道有一个列表 – Vii 2013-02-25 02:55:45

+1

这是不正确的,init方法作为设置类属性的唯一目标。 – hdante 2013-02-25 03:09:14

+0

它看起来像破碎的缩进不仅在粘贴代码。用正确的缩进来重写createLocs方法,否则python将拒绝做你想做的事。 – hdante 2013-02-25 03:15:24

1

从一个不同的角度回答。 Try ... catch,getattrdir是要走的路,如果你只是想要的代码工作。

呼叫locals()返回本地范围的字典。这是它包括self。但是,您要求selfself.locList)的孩子。孩子根本就不在字典里。最接近的事对你在做什么,应该是:

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

功能dir被查询对象的项目的通用方法。但正如其他文章中所指出的,从速度的角度来看查询对象的属性并没有什么意义。

相关问题