(课堂笔记)Python |
您所在的位置:网站首页 › 未定义函数或变量x › (课堂笔记)Python |
多态 python和其他语言相比的一大特点是,Python是dynamic的,可以接受任何数据类型,对函数参数来说,这一点同样适应,因此这也导致很多问题,比如有时候会导致很多bug,因此我们严谨的写法就是:在函数定义参数时,将其定义其参数类型,如下所示 def sum(a, b): return a + b # 将其改写为定义参数类型的 def sum(a: int, b: int): return a + b函数嵌套 python 函数另一个特性,是Python支持函数嵌套,所谓函数嵌套,就是在函数里面又有函数 如下所示: def print_1(): print('hello') def print_2(): print('world') print_2() print_1() # 输出 hello world函数嵌套的作用: 第一:函数嵌套能够保证内部函数的隐私,内部函数只能被外部函数所调用和访问,不会暴露在全局作用域,因此,如果你有一些隐私数据(如:数据库的用户和密码)不想暴露外,可以用函数嵌套,比如: def connect_DB(): def get_DB_configuration(): ... return host, username, password conn = connector.connect(get_DB_configuration()) return conn在全局作用域是无法直接调用get_DB_configuration()这个函数的,只能调用connect_DB(); 第二:合理使用嵌套能够提高代码运行的效率,比如: def factorial(input): # validation check if not isinstance(input, int): raise Exception('input must be an integer.') if input |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |