Python:在函数创建器中读取全局变量

时间:2016-04-14 03:12:54

标签: python

所以,我想创建一个函数创建器,每次调用它时都会读取一个全局变量,而不仅仅是在它被创建时。事实并非如此,因为Python将我的var引用替换为它的当前值。

import operator

space = []
pp = 0 #this is a global var

def op(op,*tval,over = 0, doSave = True):
     def operation():
        val = list(tval)
        val.append(space[pp]) # This apparently becomes val.append(space[0])
        temp = op(*val)
        if doSave:
                 space[pp] = temp # This apparently becomes space[0] = temp
     return operation

increase = op(operator.add, 1, doSave = True)

增加仅适用于空格[0],即使我更改了pp,它也只会修改空格的第一个值。

2 个答案:

答案 0 :(得分:0)

return operation

应该缩进。

你应该

global space

更改space

答案 1 :(得分:0)

假设我正确理解了您要实现的目标,您需要使function frontendvalidation(){ var emailaddbox = document.getElementById('emailaddbox').value; //var emailaddbox = document.forms["signupform"]["emailaddbox"].value; var username = document.getElementById('username').value; var password = document.getElementById('passwordbox').value; var confirmpasswordbox = document.getElementById('confirmpasswordbox').value; //Default to everything showing an error, and clear the errors as fields are validated. document.getElementById('username').style.borderColor = "red"; document.getElementById('emailaddbox').style.borderColor = "red"; document.getElementById('passwordbox').style.borderColor = "red"; document.getElementById('confirmpasswordbox').style.borderColor = "red"; // if our signup fields are empty then the border will be red if(username === '' && emailaddbox === '' && password=== '' && confirmpasswordbox=== ''){ return false; } if(username !== '' && username.length >= 5) { document.getElementById('username').style.borderColor = "green"; } if (emailaddbox !== '' ){ document.getElementById('emailaddbox').style.borderColor = "green"; } if (password !== '' && password.length <=5){ document.getElementById('passwordbox').style.borderColor = "green"; } if ( password != confirmpasswordbox){ document.getElementById('confirmpasswordbox').style.borderColor = "red"; } else if (confirmpasswordbox === password){ document.getElementById('confirmpasswordbox').style.borderColor = "green"; return true ; } } 成为全球性的。只需在pp之后添加global pp

您正在使用闭包来创建运算符,因此Python将绑定当前值def op(..)(即0)而不是全局变量的别名。如果你将pp声明为全局变量,那么别名将被绑定(Python会理解你可以改变它)。

另一项(次要)改进是将您的函数名称从pp更改为op。它不会改变功能,但会提高可读性。