Python函数创建

来源:互联网 发布:侧面导航栏网站源码 编辑:程序博客网 时间:2024/06/15 05:07

函数创建:

1.def语句

>>> def helloSomeone(who):
    "returns a salutory string customized with the input"
    return "hello" + str(who)

>>> helloSomeone("limin")
'hellolimin'

标题行由def关键字,函数的名字,以及参数的集合组成。

def子句剩余的部分包含了一个虽然可选但是强烈推荐的文档字串和必须的函数体。


2.前向引用

Python不允许在函数未声明之前,对其进行引用或者调用。

>>> foo()
in foo()
Traceback (most recent call last):
  File "<pyshell#284>", line 1, in <module>
    foo()
  File "<pyshell#283>", line 3, in foo
    tar()
NameError: name 'tar' is not defined

如果我们调用函数foo(),肯定会失败,因为函数tar()还没有声明。



我们现在定义tar()函数,在foo()函数前给出tar()的声明。

>>> def tar():
    print("in tar()")

    
>>> def foo():

print("in foo()")
    tar()

    
>>> foo()
in foo()
in tar()

现在我们可以安全的调用foo()而不会出现任何问题。


事实上我们可以在函数tar()前定义函数foo()

>>> def foo():

print("in foo()")
    tar()

>>> def tar():
    print("in tar()")

>>> foo()
in foo()
in tar()


这段代码可以非常好的运行,不会有前向引用的问题。

因为即使在(foo()中)对tar()进行的调用出现在tar()的定义之前,但foo()本身不是在tar()声明之前被调用的。

换句话谁说,我们声明foo(),然后再声明tar(),接着调用foo(),但是到那时,tar()已经存在了,所以调用成功。



3,函数属性

你可以获得每个Python模块,类和函数中任意的名称空间。你可以在模块foo()和tar()中都有名为x的一个变量,但是再将这两个模块导入你的程序后,仍然可以使用这两个变量。所以即使在两个模块中用了相同的变量名字,这也是安全的,因为句点属性标示对于两个模块意味了不同的命名空间,下面代码中就没有命名冲突。

import foo,tar

print(foo.x,tar.x)