python 函数 笔记

 

 运行 run -run module后可以在IDLE中使用函数名称

1 函数的名称反映其用途

2 给函数添加一个描述--文档字符串用于描述函数 def in_fridge():"""has a food"""

文档字符串以三引号 开头

文档字符串通过函数中的名称引用,这个名称是:__doc__    前后2个下划线 infridge.__doc__

通过dir()可以看到一个对象的所有属性

>>> dir(in_fridge)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> in_fridge.__doc__
' this is a function to see if the fridge has a food.'

3 函数创建了一个新的空间,其中名称可以被重新使用和创建,不会影响到程序的其他作用域中的相同名称。

4 即使不被使用的字符串,python也会创建它,以便将来使用

使用#添加注释,且不出现在字符串中,python将忽略它后面的所有内容,对下面一行语句开始读取剩余部分的程序

 5 不必总是将一个函数的前期版本删掉,只要最新的版本在加载时处于文件的最底部,这个最新版本将被使用。

在函数的名称后面的圆括号中使用逗号分隔参数

def in_fridge(some_fridge,desired_item):
""" this is a function to see if the fridge has a food."""
try:
count=some_fridge[desired_item]
except KeyError:
count=0
return count

6 python并不检查哪种类型的数据与函数的参数名称关联。在使用时报typeerror错误,可以使用内置函数type在函数的开头部分验证变量类型

def make_omelet(omelet_type):

"""this will make an omelet."""

  if type(omelet_type)==type({}):

    print("omelet_type is a dictionary ")

    return make_food(omelet_type,"omelet")

  elif type(omelet_type)==type(""):

  else:

    print("I don't think i can make this kind of omelet")

7 设置默认参数 ,在参数列表中使用赋值运算符=指定默认值 def make_omelet2(omelet_type="cheese"):

必须将可选参数放在参数列表的末尾。因为可选参数可能不出现

8 函数嵌套(在函数内定义函数)、函数调用

9 使用raise 全集 标记错误 raise TypeError("no such omelet type.") 遇到问题时,可以显示关于该类错误的精确信息,同进仍旧为使用都提供信息,可以被except接收和处理

10 函数层次,python在期内部创建了一个叫做栈的列表,调用栈。当调用一个函数时,pytho将停止片刻,记住程序调用函数时所处的位置,之后将该信息贮藏到它的内部列表。之后进入函数并且执行它

将代码放于try代码块中,将不会终止程序。尽量能在函数中处理掉错误

 

def do_plus(a,b):
""" this is a function add two param """
try:
total=a+b
print("a+b=%0.02f"%total)
except(TypeError) as error:
print(" type error %s"%error)
return total

 

def do_plus(a,b):
""" this is a function add two param """
if (type(a)==type(1) or type(a)==type("")) and (type(b)==type(1) or type(b)==type("")):
total=a+b
print("a+b=%0.02f"%total)
else:
raise TypeError("no such type:%s %s"%(type(a),type(b)))

return total

>>> do_plus([1,2],3)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
do_plus([1,2],3)
File "E:\pythonscript\ch5.py", line 22, in do_plus
raise TypeError("no such type:%s %s"%(type(a),type(b)))
TypeError: no such type:<class 'list'> <class 'int'>

 

posted @ 2019-08-30 14:10  caojuanshu  阅读(290)  评论(0编辑  收藏  举报