实施前置声明在Python函数 [英] Implementing forward declarations for functions in Python

查看:3283
本文介绍了实施前置声明在Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以申报功能和蟒蛇单独实现呢?
我的意思是像在C:

 无效美孚();无效美孚()
{}


解决方案

C正向声明用来解决依赖性问题。功能所使用的功能需求存在,然后才能声明它:

空白栏()
{
    如果(条件){富(); }
}无效美孚()
{
    如果(条件){栏(); }
}

不能编译,因为尚未声明之中; 无效美孚(); 我知道我在做什么,编译器,接受富后会存在

有Python中没有这样的依赖问题,因为全局名称是在运行时抬头;他们没有在编译时还不存在。

在换句话说,这个的只是工作的:

  DEF条():
    如果条件:富()高清富():
    如果条件:巴()

由于在运行时进行解析。

Is it possible to declare functions and implement them separately in python ? I mean something like in C :

void foo();



void foo() 
{

}

解决方案

C forward declarations are used to work around dependency problems. Function foo is used by function bar, and foo needs bar to exist before you can declare it:

void bar()
{
    if (condition) { foo(); }
}

void foo() 
{
    if (condition) { bar(); }
}

won't compile because foo hasn't been declared yet; void foo(); is the C spelling for I know what I am doing, compiler, accept that foo will exist later.

There are no such dependency problems in Python, as global names are looked up at runtime; they don't have to yet exist at compile time.

In other words, this just works:

def bar():
    if condition: foo()

def foo():
    if condition: bar()

because bar and foo are resolved at runtime.

这篇关于实施前置声明在Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆