@demonly
2017-10-30T14:13:03.000000Z
字数 451
阅读 666
Python
使用 def 语句可以定义函数,在函数开头插入一个字符串可以作为文档字符串。可以使用 =
来指定参数默认值。
def hello(name):
'document'
return 'Hello, ' + name + '!'
在参数前加 *
收集剩余参数,在参数前加 **
收集关键字参数。
def print_params(x, y, z=3, *pospar, **keypar):
print x, y, z
print pospar
print keypar
print_params(1, 2, 3, 5, 6, 7, foo=1, bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
函数调用时在参数前加 *
展开序列,在参数前加 **
可以展开字典作为关键字参数。
class 语句定义类,将其他类名卸载 class 语句后的圆括号内指定超类,声明对象的方法时可以指定一个 self 参数来取得对象本身的引用,这个参数不需要手动传入。
在 Python 的函数中访问全局变量需要先用 global 关键字声明,访问外部作用域需要先用 nolocal 关键字声明