您的位置:首页 > 编程语言 > Python开发

[python] 第7章 函数 第8章 模块

2013-11-02 13:04 501 查看
*********************************

**          第7章 函数          **

#!/usr/bin/env python
# Filename: func_local.py
def func(x):
print 'x is',x
x = 2
print 'Changed local x to',x
x = 50
func(x)
print 'x is still',x
结论 : 局部变量不会影响到全局变量。解决 : 使用global语句
#!/usr/bin/python
#Filename: func_global.py
def func():
global x, y
print 'x is', x
x = 2
print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x

7.5 使用默认参数值
#!/usr/bin/python
# Filename: func_default.py
def say(message, times = 1):
print message * times
say('Hello')
say('World', 5)

7.6 使用关键参数
#!/usr/bin/python
# Filename: func_key.py
def func(a, b=5, c=10):
print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
输出
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

注意,没有返回值的return语句等价于return None。None是Python中表示没有任何东西的特殊类型。 例如,如果一个变量的值为None,可以表示它没有值。

  pass 语句在Python中表示一个空的语句块。

7.8 使用DocStrings  Python有一个很奇妙的特性,称为 文档字符串 ,它被简称为docstrings
#!/usr/bin/python
# Filename: func_doc.py
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'
printMax(3, 5)
print printMax.__doc__

输出

$ python func_doc.py

5 is maximum

Prints the maximum of two numbers.

        The two values must be integers.

请记住Python把 每一样东西 都作为对象,包括这个函数。

*********************************

**          第8章 模块          **

*********************************

8.1 使用sys模块
#!/usr/bin/python
# Filename: using_sys.py
import sys
print 'The command line arguments are:'
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'

sys.argv变量是一个字符串的 列表。特别地,sys.argv包含了 命令行参数 的列表,即使用命令行传递给你的程序的参数。

字节编译的.pyc文件, .pyc文件是十分有用的——它会快得多

8.2 模块的__name__

#!/usr/bin/python
# Filename: using_name.py
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'

例8.3 如何创建你自己的模块
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
###### End of mymodule.py  ######

#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version

下面是一个使用from..import语法的版本。
#!/usr/bin/python
# Filename: mymodule_demo2.py
from mymodule import sayhi, version
sayhi()
print 'Version', version
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: