# 名字解析 (程序设计)

## 静态解析与动态解析

```>>> locals()['num'] = 999 # equivalent to: num = 999
>>> noun = "troubles"
>>> noun2 = "hound"
>>> # which variables to use are decided at runtime
>>> print("{num} {noun} and a {noun2} ain't one".format(**locals()))
999 troubles and a hound ain't one
```

## 名字屏蔽

```  private int foo;  // A declaration with name "foo" in an outer scope
public void setFoo(int foo) {  // A declaration with the same name in the inner scope
// "foo" is resolved by looking in the innermost scope first,
// so the author uses a different syntax, this.foo, to refer to the name "foo"
// in the outer scope.
this.foo = foo;
}
// "foo" here means the same as this.foo below,
// since setFoo's parameter is no longer in scope.
public int getFoo() { return foo; }
```

## α更名简化了名字解析

```  class Point {
private:
double x, y;

public:
Point(double x, double y) {  // x and y declared here mask the privates
setX(x);
setY(y);
}

void setX(double newx) { x = newx; }
void setY(double newy) { y = newy; }
}
```

Point构造函数中，类的数据成员xy被局部变量屏蔽了。这可通过α更名改善：

```  class Point {
private:
double x, y;

public:
Point(double a, double b) {
setX(a);
setY(b);
}

void setX(double newx) { x = newx; }
void setY(double newy) { y = newy; }
}
```

## 参考文献

1. ^ [Python-Ideas] str.format utility function. 9 May 2009 [2011-01-23]. （原始内容存档于2018-07-14）.
2. ^ 8.6. Dictionary-based string formatting. diveintopython.org. Mark Pilgrim. [2011-01-23]. （原始内容存档于2019-12-23）.
3. ^ 9. Classes - Python v2.7.1 documentation. [2011-01-23]. （原始内容存档于2012-10-23）. search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution