你可以在声明之前修改变量吗?

时间:2015-10-01 16:28:42

标签: python python-2.7 python-3.x globals

我有数百个变量(这里只有少数几个,所以你会知道这个代码是如何工作的),我不知道如何解决这个问题。我想做的是在第二个if语句以某种方式修改变量,然后声明它,所以我可以复制类到它,所以我可以绕过许多不必要的如果声明。有可能吗?

此代码在第二个if语句当然不正确

globals()["p%sg%sr01_id" % (cp, awsg)]) = copy.copy(temp1)

但这是我在声明变量之前想要实现的,我将复制类

import copy
cp = "01"
awsg = "01"
temp1 = 0
temp2 = 0

first_hovered_variable = "01"
second_hovered_variable = "02"


class Char():
    def __init__(self, name):
        self.n = name

p01g01r01_id = Char("A1")
p01g01r02_id = Char("B2")
p01g01r03_id = Char("C3")

reg01_id = Char("001")
reg02_id = Char("002")
reg03_id = Char("003")


def swap_variables():
    global cp
    global awsg

    global temp1
    global temp2

    global first_hovered_variable
    global second_hovered_variable

    global reg01_id
    global reg02_id
    global reg03_id

    global p01g01r01_id
    global p01g01r02_id
    global p01g01r03_id

    if first_hovered_variable == second_hovered_variable:
        first_hovered_variable = 0
        second_hovered_variable = 0

    elif first_hovered_variable != 0 and second_hovered_variable != 0:
        temp1 = copy.copy(globals()["p%sg%sr%s_id" % (cp, awsg, second_hovered_variable)])
        temp2 = copy.copy(globals()["p%sg%sr%s_id" % (cp, awsg, first_hovered_variable)])

        if first_hovered_variable == "01":
            reg01_id = copy.copy(temp1)
            globals()["p%sg%sr01_id" % (cp, awsg)]) = copy.copy(temp1)

        elif first_hovered_variable == "02":
            reg02_id = copy.copy(temp1)
            globals()["p%sg%sr02_id" % (cp, awsg)]) = copy.copy(temp1)

        elif first_hovered_variable == "03":
            reg03_id = copy.copy(temp1)
            globals()["p%sg%sr03_id" % (cp, awsg)]) = copy.copy(temp1)    

        if second_hovered_variable == "01":
            reg01_id = copy.copy(temp2)
            globals()["p%sg%sr01_id" % (cp, awsg)]) = copy.copy(temp1)    

        elif second_hovered_variable == "02":
            reg02_id = copy.copy(temp2)
            globals()["p%sg%sr02_id" % (cp, awsg)]) = copy.copy(temp1)

        elif second_hovered_variable == "03":
            reg03_id = copy.copy(temp2)
            globals()["p%sg%sr03_id" % (cp, awsg)]) = copy.copy(temp1)

    temp1 = 0
    temp2 = 0

swap_variables()
print p01g01r01_id.n
print p01g01r02_id.n
print p01g01r03_id.n

print reg01_id.n
print reg02_id.n
print reg03_id.n

1 个答案:

答案 0 :(得分:4)

是的,您可以直接在globals()目录中设置新的全局变量,而无需对这些名称使用任何其他分配。

但是,您应该考虑为您的实例创建单独的字典或列表。这样,您就可以将这些实例作为一个组来处理。

对于3个维度,您甚至可以生成嵌套结构:

characters = [
    [
        [Char(letter + digit) for letter, digit in zip('ABC', '123')]
        for g in range(3)
    ] for p in range(3)
]

对3个reg变量执行相同操作;将它们存储在列表中。

现在,您可以在characters[0][1][2]处理Char('C3')以获得该位置。将这些索引存储在变量中,您可以使用那些来处理不同的位置:

reg[first_hovered_variable] = characters[cp][awsg][first_hovered_variable]

您删除了一整套if语句。