python-函数

来源:互联网 发布:淘宝网吧二手电脑 编辑:程序博客网 时间:2024/06/05 00:25

python基本里面的所有东西都是对象,

一:创建一个函数

 def Myfonction(title):'你好是的,这是文字'# 哈哈哈,我猜也是的,就是这样的。print('牛气了,' + title + '哈哈啊')

其中这里是函数文档'你好是的,这是文字'

打印方法

1:Myfonction.__doc__
2:help(Myfonction)


二:关键字参数:

def SaySome(name,words):print(name + '->'+  words)
SaySome(words = '是一个动物', name = '猫')猫->是一个动物

让关键字直接定义,以免出现定义错误的问题。

三:收集参数:

def test(*params):print('参数的长度:',len(params));
test(23,2 ,3, 3,4)参数的长度: 5
定义函数的时候,在参数前加了一个 * 号,函数可以接收零个或多个值作为参数。返回结果是一个元组。

2:收集参数形式:

>>> def useDic(**ke):print(ke['name'], 'is', ke['age'], 'years old')>>> args = {'name':'hili', 'age':23}>>> useDic(**args)hili is 23 years old

四:函数

python 所有函数都是会返回某些东西的。 是动态的确定类型。编译器确定类型。

>>> def hello():print()>>> hello()>>> print(hello())None

五:返回多个值

>>> def back():return [1, '兄弟哦', 2]>>> back()[1, '兄弟哦', 2]>>> def bacn():return 2, 35, '234'>>> bacn<function bacn at 0x1057eb598>>>> bacn()(2, 35, '234')


六:局部变量和全局变量


def Dis(price, rate):        final_price = price * rate        #print('前前前---方法的原价是:',old_price)        old_price = 23        print('方法里的原价是:', old_price)        return final_priceold_price = float(input('请输入原价:'))rate = float(input('请输入折扣率:'))new_price = Dis(old_price, rate)print('打折后价格是:', new_price)print('原来的原价是:', old_price)#print('这里视图打印局部变量final_price:', final_price)####################后面的注意,会不执行,因old_price = 111。后续讲解如何修改全局变量def DisNew(price,rates):    print('后后后后:', old_price)    old_price = 111    print('现现现现现:', old_price)    new_pirceodl = DisNew(old_price, rate)

#输出结果:请输入原价:123请输入折扣率:1方法里的原价是: 23打折后价格是: 123.0原来的原价是: 123.0Traceback (most recent call last):  File "/Users/hongbaodai/Desktop/Untitled.py", line 21, in <module>    new_pirceodl = DisNew(old_price, rate)  File "/Users/hongbaodai/Desktop/Untitled.py", line 17, in DisNew    print('后后后后:', old_price)UnboundLocalError: local variable 'old_price' referenced before assignment>>> 

Dis方法里old_price = 23能执行是因为在Dis方法里生成了一个局部变量old_price,这个在栈里,出作用域即销毁。所以跟下面的全局变量old_price不是一个。

七:在函数中修改全局变量

cout = 3def myfun():    global cout    cout = 224    print(cout)print(cout)myfun()print(cout)

结果:3224224

这里加上关键字global就可以修改全局变量cout。

八:闭包

容器类型不是存放在栈里面,所以可以进行修改

def FunY(x):    def FunX(y):        return x * y    return FunX
i = FunY(2)itype(i)i(2)fun(2)(2)

结果>>> i (2)4>>> FunY(2)(2)4


FunX就是一个闭包

但是闭包有一个需要注意的地方:就是内部对外部局部变量的修改

例如 这么写会报错def fun1(x):x = 2def fun2(y):x *= xreturn xreturn fun2

解决方案:加上关键字nonlocal.

def fun1(x):x = 2def fun2(y):nonlocal xx *= xreturn xreturn fun2
调用 >>> fun1(1)(1)4

九:匿名函数:lambda

正规函数写法:>>> def ds(x):return x * 2 + 2>>> ds(2)6

匿名函数写法:<function <lambda> at 0x10581e9d8>>>> g = lambda x : x * 2 + 2>>> g(2)6>>> g = lambda x : x * 2 + 6>>> g(2)10

多参数写法:>>> g = lambda x, y : x  +y>>> g(1, 3)4


十:函数:map() 和 filter()

map():

map(function, iterable, ...)Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

map函数使用自定义的function处理iterable中的每一个元素,将所有的处理结果以list的形式返回

>>> list(map(lambda x : x % 2, range(10)))[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

filter()

filter(function, iterable)Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.
function是判断函数)参数function(是函数)用于处理iterable中的每个元素,如果function处理某元素时候返回true,那么该元素将作为list的成员而返回。
>>> list(filter(lambda x : x % 2, range(10)))[1, 3, 5, 7, 9]










原创粉丝点击