0

I have a long list of if statements that are checking if an object (self) contains a series of optional attributes.

As an example:

if(hasattr(self, variableList)):
    var1 = self.var1

if(hasattr(self, "var2")):
    var2 = self.var2  

if(hasattr(self, "var3")):
    var3 = self.var3

if(hasAttr(self, "var4")):
    var4 = self.var4

I was trying to figure out if there was a simple way of using a for loop that would use variable names from a list to check the object, and if they exist to store them locally in the method, which I think would require a dictionary in some way. Is it bad practice to try the above? Would it be more appropiate to have the more explicit list or to reduce the code with something like

for x in variableList:
    if(hasattr(self,variableList[x]))
        localvariable = variableList[x]
4

2 回答 2

1

每个对象都有一个__dict__将实例成员存储在字典中的属性。对于高度动态/内省的事物非常有用。例如:

class c():
    def __init__(self):
        self.a = 1
    def test(self):
        print self.__dict__


>>> o = c()
>>> o.test()

印刷

{'a': 1}

编辑:getattr可能是比更好的建议__dict__

另一个有用的花絮是locals()您可以读写的局部变量字典。

例如:

>>> locals()["TEST"] = 1
>>> TEST

印刷

1

从这两个事实来看,你应该能够做任何你想做的事情。这是否是一个好主意是一个完全不同的故事。:)(我猜可能不是。请参阅@mgilson 的评论)。

于 2014-07-28T21:08:29.343 回答
1

这应该适合你:

var_list = ['var1', 'var2', 'var3'] # create list of variable string names

for var in var_list: # iterate over list of variable names

    try:
        # use exec to execute assignments, assuming attribute exists
        exec('{0} = {1}'.format(var, getattr(self, var))) 

    except AttributeError: # catch the Exception if the attribute does not exist

        exec('{0} = None'.format(var)) # set var to some default value, whatever
                                       # is convenient for later code to check
                                       # for and handle

正如评论中其他人所建议的那样,您似乎使用了一个奇怪的构造。在你的代码工作之后,我建议你把它交给CodeReview并询问更好的方法来实现你想要做的事情。没有看到你的其余代码很难说,但我怀疑有更好的方法来实现你的总体目标。

于 2014-07-28T21:03:42.827 回答