Python学习笔记之抽象

一、创建函数

>>> import math

>>> x=1

>>> y=math.sqrt

>>> callable(x) #显示False

>>> callable(y) #显示True

1、def,用来创建函数

>>> def hello(name)

>>>  return 'Hello, '+name+'!'

>>> print(hello('world'))

显示:Hello, world

2、为函数增加说明

>>> def square(x):

>>>  'Calculates the square of the number x.'

>>>  return x *x

>>> square.__doc__

显示:'Calculates the square of the number x.'

通过help查看函数

>>> help(square)

二、函数参数

1、抽象函数

>>> def init(data):

>>>  data['first']={}

>>>  data['middle']={}

>>>  data['last']={}

>>> storage={}

>>> init(storage)

>>> storage

显示:{'middle':{},'last':{},'first':{}}

2、收集参数

>>> def print_params(x,y,z=3,*pospar,**keypar)

>>>  print(x,y,z)

>>>  print(pospar)

>>>  print(keypar)

显示:1 2 3    (5,6,7)  {'foo':1,'bar':2}

注:‘*’,单个星号用来联合普通参数,‘**’,两个星号用来处理关键字

3、power计算乘积

>>> power(3,2)

显示:9

4、interval,间隔

>>> interval(10)

显示:[0,1,2,3,4,5,6,7,8,9]

>>> interval(1,5)

显示:[1,2,3,4]

5、当参数名和全局变量名一样时,全局变量会被屏蔽,不能直接访问,如果要想访问,就需要借助globals

>>> def combine(parameter):

>>>  print(parameter+globals()['parameter'])

>>> parameter='berry'

>>> combine('Shrub')

显示:Shrubberry

原文地址:https://www.cnblogs.com/xiaofoyuan/p/5535439.html