1.1 模块
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 自定义模块 myModule.py
def func():
print "MyModule.func()"
class MyClass:
def myFunc(self):
print "MyModule.MyClass.myFunc()"
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#调用自定义模块的类和函数
import myModule
myModule.func()
myClass = myModule.MyClass()
myClass.myFunc()
输出:
>>>
MyModule.func()
MyModule.MyClass.myFunc()
>>>
#!/usr/bin/env python
#-*- coding:utf-8 -*-
print '*' * 50 #注意,module_import.py 中有这行,第一次import时会被执行
def func0():
print "I am the zero func"
def func1(one):
print "Iam the one func1 about %s" % one
def func2(two):
''' hello ,this is a test about the text of function'''
print "This is the second func2 about %s " % two
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from module_import import func0
************************************************** #第一次import时会被执行
>>> func0()
I am the zero func
>>> from module_import import func1 #没有了打印星号
>>> func1('me')
Iam the one func1 about me
>>> from module_import import func2
>>> func2('you')
This is the second func2 about you
>>>
以上单独调用了自定义的函数,看下面就会出现问题
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> func0()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'func0' is not defined
>>> import module_import
**************************************************
>>> func0()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'func0' is not defined
>>> func1('me')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'func1' is not defined
>>>
直接调用某个文件,根本就不能调用其中的自定义函数,但是文件中的打印执行了,说明如果该文件中有直接执行的内容,则在调用时会被执行;
但是如下方法可以:
>>> module_import.func1('me')
Iam the one func1 about me
>>> module_import.func0()
I am the zero func
>>> module_import.func2('you')
This is the second func2 about you
>>>
例 2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 自定义模块myModule.py
from copy import deepcopy
count = 1
def func():
global count
count = count + 1
return count
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import myModule
print "count =", myModule.func()
myModule.count = 10
print "count =", myModule.count
import myModule
print "count =", myModule.func()
# import置于条件语句中
if myModule.count > 1:
myModule.count = 1
else:
import myModule
print "count =", myModule.count
输出:
>>>
count = 2
count = 10
count = 11
count = 1
>>>
模块的属性:
# 自定义模块myModule.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
print 'myModule作为主程序运行'
else:
print 'myModule被另一个模块调用'
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'description'
import myModule
print __doc__
>>>
myModule作为主程序运行
>>>
>>>
myModule被另一个模块调用
description
>>>
1.2 函数调用(内置函数)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
print bool(0) #布尔逻辑判断
print buffer("dabcet",1,3) #输出指定字符的2-4个
print cmp(0,1) #比较,大于为1,等于输出0,小于为-1
print coerce(1,2) #对参数进行组合,返回元组;
print zip((1,2),(3,4)) #对元组进行打包,返回列表;
>>>
False
abc
-1
(1, 2)
[(1, 3), (2, 4)]
>>>
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# apply()
def sum(x=1, y=2):
return x + y
print apply(sum, (1, 3)) #对1,3 求和
print '\n'
# filter()
def func(x):
if x > 0:
return x
print filter(func, range(-9, 10)) #输出大于0的数
print '\n'
# reduce()
def sum(x, y):
return x + y
print reduce(sum, range(0, 10)) #0到10累加求和
print reduce(sum, range(0, 10), 10) #0到10累加求和后再加10
print reduce(sum, range(0, 0), 10) #0到0累加求和后再加10
print '\n'
# map()
def power(x): return x ** x #输出平方
print map(power, range(1, 5)) #x的x次方
def power2(x, y): return x ** y
print map(power2, range(1, 5), range(5, 1, -1)) # 蓝色部分5开始依次减1,直到为2
>>>
4
[1, 2, 3, 4, 5, 6, 7, 8, 9]
45
55
10
[1, 4, 27, 256]
[1, 16, 27, 16] #1的5次方为1, 2的4次方为16,3的3次方27,4的平方16,就这样来的;
>>>
1.3 自定义函数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 函数的定义
from __future__ import division
def arithmetic(x, y, operator):
result = {
"+" : x + y,
"-" : x - y,
"*" : x * y,
"/" : x / y
}
return result.get(operator) # 返回计算结果
# 函数的调用
print arithmetic(1, 2, "+")
>>>
3
>>>
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import division
def append(args=[]):
if len(args) <= 0:
args = []
args.append(0)
print args
append()
append([1])
append()
print '\n'
# 函数的缺省参数
def arithmetic(x=1, y=1, operator="+"):
result = {
"+" : x + y,
"-" : x - y,
"*" : x * y,
"/" : x / y
}
return result.get(operator) # 返回计算结果
print arithmetic(1, 2)
print arithmetic(1, 2, "-")
print arithmetic(y=3, operator="-")
print arithmetic(x=4, operator="-")
print arithmetic(y=3, x=4, operator="-")
print '\n'
# 列表作为参数传递
def arithmetic(args=[], operator="+"):
x = args[0]
y = args[1]
result = {
"+" : x + y,
"-" : x - y,
"*" : x * y,
"/" : x / y
}
return result.get(operator) # 返回计算结果
print arithmetic([1, 2])
print '\n'
# 传递可变参数
def func(*args):
print args
func(1, 2, 3)
print '\n'
# 传递可变参数
def search(*t, **d):
keys = d.keys()
values = d.values()
print keys
print values
for arg in t:
for key in keys:
if arg == key:
print "find:",d[key] #字典
search("one", "three", one="1",two="2",three="3")
>>>
[0]
[1, 0]
[0]
3
-1
-2
3
1
3
(1, 2, 3)
['three', 'two', 'one']
['3', '2', '1']
find: 1
find: 3
>>>
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# return语句
from __future__ import division
def arithmetic(x, y, operator):
result = {
"+" : x + y,
"-" : x - y,
"*" : x * y,
"/" : x / y
}
return result.get(operator) # 返回计算结果
# 没有return语句的函数返回None
def func():
pass
print func()
# return后不带参数
def func():
return
print func()
# return返回多个值
def func(x, y, z):
l = [x, y, z] #赋给列表
l.reverse() #翻转
numbers = tuple(l) #转换成元组
return numbers
x, y, z = func(0, 1, 2)
print x, y, z
# return返回多个值
def func(x, y, z):
l = [x, y, z]
l.reverse()
a, b, c = tuple(l)
return a, b, c
x, y, z = func(0, 1, 2)
print x, y, z
# 多个return语句
def func(x):
if x > 0:
return "x > 0"
elif x == 0:
return "x == 0"
else:
return "x < 0"
print func(-2)
# 多个return语句的重构
def func(x):
if x > 0:
result = "x > 0"
elif x == 0:
result = "x == 0"
else:
result = "x < 0"
return result
print func(-2)
>>>
None
None
2 1 0
2 1 0
x < 0
x < 0
>>>
函数嵌套:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 嵌套函数
def sum(a, b):
return a + b
def sub(a, b):
return a - b
def func():
x = 1
y = 2
m = 3
n = 4
return sum(x, y) * sub(m, n)
print func()
# 调用内部函数
def func():
x = 1
y = 2
m = 3
n = 4
def sum(a, b): # 内部函数
return a + b
def sub(a, b): # 内部函数
return a - b
return sum(x, y) * sub(m, n)
print func()
# 内部函数直接使用外层函数的变量
def func():
x = 1
y = 2
m = 3
n = 4
def sum(): # 内部函数
return x + y
def sub(): # 内部函数
return m - n
return sum() * sub()
print func()
>>>
-3
-3
-3
>>>
函数递归:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 计算阶乘
def refunc(n):
i = 1
if n > 1: # 递归的结束判断
i = n
n = n * refunc(n-1) # 递推
print "%d! =" %i, n
return n # 回归
refunc(5)
# 使用reduce计算阶乘
print "5! =", reduce(lambda x, y: x * y, range(1, 6))
>>>
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
5! = 120
>>>
lambda的函数用法
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# lambda
def func():
x = 1
y = 2
m = 3
n = 4
sum = lambda x, y : x + y
print sum
sub = lambda m, n : m - n
print sub
return sum(x, y) * sub(m, n)
print func()
print '\n'
# lambda的函数用法
print (lambda x: -x)(-2) #-2 传递给-x
>>>
<function <lambda> at 0x02124970>
<function <lambda> at 0x02124630>
-3
2
>>>
Generator函数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 定义Generator函数
def func(n):
for i in range(n):
yield i
# 在for循环中输出
for i in func(3):
print i
# 使用next()输出
r = func(3)
print r.next()
print r.next()
print r.next()
#print r.next()
# yield与return区别
def func(n):
for i in range(n):
return i
def func2(n):
for i in range(n):
yield i
print func(3)
f = func2(3)
print f
print f.next()
print f.next()
>>>
0
1
2
0
1
2
0
<generator object func2 at 0x02068710>
0
1
>>>
拓展:
- lambda arg1,arg2... : <expression>
- lambda x: print x
- L = [lamba x: x**2, lambda x: x**3]
- ((test and [x]) or [y])[0]
- (test and x) or y
- (test and 0) or []
- ((test and [0]) or [[]])[0]
- F=lambda x: map((lambda y: y**2), x)
- import sys
- pp = lambda x: sys.stdout.write(str(x)+'/n')
- pp(8) ===> 8
>>> def f(x): ... return x*2 ... >>> f(3) 6 >>> g = lambda x: x*2 >>> g(3) 6 >>> (lambda x: x*2)(3) 6
总的来说,lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值。lambda 函数不能包含命令,包含的表达式不能超过一个。不要试图向lambda 函数中塞入太多的东西;如果你需要更复杂的东西,应该定义一个普通函数,然后想让它多长就多长。
lambda 函数是一种风格问题。不一定非要使用它们;任何能够使用它们的地方,都可以定义一个单独的普通函数来进行替换。我将它们用在需要封装特殊的、非重用代码上,避免令我的代码充斥着大量单行函数。 |
本文来自博客园,作者:{Julius},转载请注明原文链接:https://www.cnblogs.com/bestechshare/p/16447900.html
可微信加我,了解更多,WeChat:{KingisOK}