创建函数

内建的callable函数可用于判断函数是否可调用;函数callable在Python 3.0中不再可用,需要使用表达式hasattr(func, __call__)代替;

1.文档化函数

在函数开头写下字符串,就会作为函数的一部分进行存储,称为文档字符串;

def square(x):
    'Calculates the square of the number x.'
    return x*x
square.__doc__         # 'Calculates the square of the number x.'
                       # 访问文档字符串

内建的help函数可以再交互式解释器中使用,可以得到关于函数(包括文档字符串)的信息;

2.并非真正的函数

  • 没有return函数或return后没有返回值的函数不返回值;
  • return语句可以起到结束函数的作用;
  • 调用没有返回值的函数,返回None;

results matching ""

    No results matching ""