ToB企服应用市场:ToB评测及商务社交产业平台

标题: python教程:自定义函数 [打印本页]

作者: 傲渊山岳    时间: 2024-7-4 15:03
标题: python教程:自定义函数
1.多态

我们可以看到,Python 不用思量输入的数据类型,而是将其交给具体的代码去判定执行,同样的一个函数(比如这边的相加函数 my_sum()),可以同时应用在整型、列表、字符串等等的操作中。
在编程语言中,我们把这种行为称为多态。这也是 Python 和其他语言,比如 Java、C 等很大的一个不同点。当然,Python 这种方便的特性,在实际利用中也会带来诸多问题。因此,必要时请你在开头加上数据的类型查抄。
  1. def my_sum(a, b):
  2.     if type(a) == type(b):
  3.         if isinstance(a, (int, str, list)):
  4.             return a + b
  5.         else:
  6.             raise Exception("input is not int/str/list")
  7.     else:
  8.         raise Exception("input type is not same")
  9. print(my_sum(3, 5))
  10. # 输出
  11. # 8
  12. print(my_sum([1, 2], [3, 4]))
  13. # 输出
  14. # [1, 2, 3, 4]
  15. print(my_sum('hello ', 'world'))
  16. # 输出
  17. # hello world
  18. print(my_sum([1, 2], 'hello'))
  19. # 输出
  20. # input type is not same
复制代码
2.函数嵌套

Python 函数的另一大特性,是 Python 支持函数的嵌套。所谓的函数嵌套,就是指函数里面又有函数,比如:
  1. def f1():
  2.     print('hello')
  3.     def f2():
  4.         print('world')
  5.     f2()
  6. f1()
  7. # 输出
  8. hello
  9. world
复制代码
嵌套带来的好处
内部函数只能被外部函数所调用和访问,不会暴露在全局作用域,因此,假如你的函数内部有一些隐私数据(比如数据库的用户、密码等),不想暴露在外,那你就可以利用函数的的嵌套,将其封装在内部函数中,只通过外部函数来访问。比如:
  1. def connect_DB():
  2.     def get_DB_configuration():
  3.         ...
  4.         return host, username, password
  5.     conn = connector.connect(get_DB_configuration())
  6.     return conn
复制代码
这里的函数 get_DB_configuration 是内部函数,它无法在 connect_DB() 函数以外被单独调用。也就是说,下面这样的外部直接调用是错误的:
  1. get_DB_configuration()
  2. # 输出
  3. NameError: name 'get_DB_configuration' is not defined
复制代码
看下面这个例子:
[code]def factorial(input):    # validation check    if not isinstance(input, int):        raise Exception('input must be an integer.')    if input < 0:        raise Exception('input must be greater or equal to 0' )    def inner_factorial(input):        if input




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4