静态/动态范围、类型、绑定

Adi*_*rma 5 c++ python scope

我问这个只是为了澄清我的想法是否正确。

静态/动态类型 如果在编译时变量的类型是已知的,则语言是静态类型的。这实际上意味着您作为程序员必须指定每个变量的类型。示例:Java、C、C++。

如果在运行时解释变量的类型,则语言是动态类型化的。这意味着您作为程序员可以更快地编写代码,因为您不必每次都指定类型。示例:Perl

Static/Dynamic Binding——下面的链接清楚地解释了Static Binding和Dynamic Binding的区别

我想问的主要问题从这里开始。我知道静态范围和动态范围之间的区别。然而,当我经历堆栈溢出时,人们说 C++ 和 Python 是静态作用域的。

在 C++ 中,如果我输入

int void main(){
   cout<<i;          
   int i=15;
}  
int i=10;
Run Code Online (Sandbox Code Playgroud)

它可以工作(即使在 java 中)。但是它的 python 等价物

def foo():
    print(x)
    x=10
x='global'
foo()
Run Code Online (Sandbox Code Playgroud)

给出一个错误。

Ore*_*era 4

在 Python 和 C++ 中,作用域都是静态的。这些语言之间的差异与定义名称范围的开始和结束的规则有关。

\n\n

在 C++ 中,变量i在局部定义之前被视为全局变量int i=15;

\n\n

在 Python 中:\n Python 中局部变量和全局变量的规则是什么?:

\n\n
\n

如果在函数体内的任何位置给变量赋值,则除非显式声明为全局变量,否则它\xe2\x80\x99s 被假定为局部变量。

\n
\n\n

命名和绑定

\n\n
\n

当代码块中使用名称时,将使用最近的封闭范围来解析该名称。

\n
\n\n

因此,由于该变量x是在内部分配的,foo()因此假定它是从函数开头开始的局部变量foo()。\n可以x使用关键字将整个功能块视为全局变量global

\n\n
def foo():                \n    global x              # name \'x\' refers to the global variable\n    print(x)              # print global \'x\'\n    x=10                  # assign global variable\n\nx=\'global\'\nfoo() # print \'global\'\nfoo() # print \'10\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

x实际上,即使您想使用build-it 函数x在同一函数中拥有本地名称,也可以访问全局变量:globals()

\n\n
def foo():                # name \'x\' refers to the local variable\n    print(globals()[\'x\']) # access the global name \'x\'\n    x=10                  # assign local variable\n    print(x)              # print local \'x\'\n\nx=\'global\'\nfoo()\n
Run Code Online (Sandbox Code Playgroud)\n