我有一个全局变量ser
,我需要在某些情况下删除它:
global ser
ser = ['some', 'stuff']
def reset_ser():
print('deleting serial configuration...')
del ser
如果我致电reset_ser()
,我会收到错误消息:
UnboundLocalError: local variable 'ser' referenced before assignment
如果我将全局变量作为输入提供给函数我不会得到错误,但是变量不会被删除(我猜只是在函数本身内部)。有没有办法删除变量,或者我是否要覆盖它以摆脱它的内容?
答案 0 :(得分:10)
在函数中使用global ser
:
ser = "foo"
def reset_ser():
global ser
del ser
print(ser)
reset_ser()
print(ser)
输出:
foo
Traceback (most recent call last):
File "test.py", line 8, in <module>
print(ser)
NameError: name 'ser' is not defined
答案 1 :(得分:1)
您可以使用以下命令将其从全局范围中删除:
object Example {
sealed trait Status
case object Student extends Status
case object Unemployed extends Status
case object Other extends Status
object PoorStudent {
def unapply(income: Int) = if (income <= 18000) Some(income) else None
}
object PoorUnemployed {
def unapply(income: Int) = if (income <= 7000) Some(income) else None
}
object IncomeScoreRange {
def unapply(score: Int, income: Double) =
if (((score < 100 || score > 150) && income <= 8500) || (income <= 10500 && (100 to 167 contains score)))
Some((score, income))
else
None
}
def compute(status: Option[Status], score: Option[Int], income: Option[Double]): String = {
(status, score, income).zipped
.collect {
case (Student, _, PoorStudent(_)) => "P"
case (Unemployed, _, PoorUnemployed(_)) => "P"
case (Other, IncomeScoreRange(_, _)) => "P"
}
.headOption
.getOrElse("F")
}
}
更完整的例子:
del globals()['ser']