解决方法在for循环中覆盖局部变量?

时间:2015-11-05 23:49:08

标签: python

我的代码是这样的:

funcs = []

class NumberContainer():
    def __init__(self, num):
        self.number = num

items = []
for i in range(5):
    items.append(NumberContainer(i+1))

for item in items:
    number = item.number
    n = number
    def my_func(x):
        res = x < n
        print("is {} less than {}? {}".format(x, number, res))
        return res
    funcs.append(my_func)

for f in funcs:
    f(3)

此输出:

is 3 less than 5? True
is 3 less than 5? True
is 3 less than 5? True
is 3 less than 5? True
is 3 less than 5? True 

但显然我真正想要的是检查数字的范围。

我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

解决方案(通常是这种情况)是不使用全局变量(或非本地变量)。您的函数输入应来自参数,输出应该是返回值。至于构建功能,我会使用某种工厂..

在这种情况下,我会写:

/** Some mathematical utilities */
public final class MathUtils {

  /**
   * The number of unique {@code double} values between {@code a} and
   * {@code b}.
   * 
   * @param a
   *          the first {@code double}
   * @param b
   *          the second {@code double}
   * @return the steps between them, or {@code -1} if either value is
   *         {@link Double#NaN} or both are infinities of different signs
   */
  public static final long difference(final double a, final double b) {
    final long bitsA;
    double useA, useB, temp;

    if ((a != a) || (b != b)) { // take are of NaN
      return -1L;
    }
    useA = (a + 0d);
    useB = (b + 0d);
    if (useA > useB) {
      temp = useB;
      useB = useA;
      useA = temp;
    }
    if (useA == useB) {
      return 0L;
    }
    if (useA <= Double.NEGATIVE_INFINITY) {
      return -1L;
    }
    if (useB >= Double.POSITIVE_INFINITY) {
      return -1L;
    }

    if (useA < 0d) {
      bitsA = Double.doubleToRawLongBits(-useA);
      if (useB < 0d) {
        return (bitsA - Double.doubleToRawLongBits(-useB));
      }
      return (bitsA + Double.doubleToRawLongBits(useB));
    }
    return (Double.doubleToRawLongBits(useB)
        - Double.doubleToRawLongBits(useA));
  }
}