![](/img/trans.png)
[英]Python Class. key exists as self.key, but doesn't exists in self.__dict__
[英]Checking if a Variable Exists in Python - Doesn't work with 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()
我想你想要hasattr(self,'locList')
虽然,你通常最好不要尝试使用属性并捕获如果不存在而引发的AttributeError
:
try:
print self.locList
except AttributeError:
self.locList = "Initialized value"
从一个不同的角度回答。 如果你只想让代码工作, Try ... catch
, getattr
或dir
就是你的选择。
调用locals()
返回本地范围的字典。 那就是它包括self
。 但是,你要求self
的孩子( self.locList
)。 孩子根本就不在字典里。 与你正在做的最接近的事情是:
if 'locList' in dir(self):
print 'it exists'
function dir
是查询对象项的通用方法。 但正如其他帖子所述,从速度角度查询对象的属性没有多大意义。
您可以使用带有默认值的try / except或getattr,但这些对您的代码没有意义。 __init__方法用于初始化对象:
def __init__(self):
self.locList = []
允许locList不存在是没有意义的。 零长度列表是没有位置的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.