• 22 【python】入门指南:函数


    #!/bin/python
    
    def test_func():
        return "test_func"
    
    a = test_func()
    print(a)

    输出结果:

    test_func

    形式2:带两个参数,返回他们的乘积值

    #!/bin/python
    
    #return a * b
    #a: int | float
    #b: int | float
    def multiply(a, b):
        return a * b
    
    t = multiply(100, 20)
    print(t)

    输出结果:2000

    这里需要对两个参数说明下,包括他们的类型。因为python是动态语言,定义函数的时候不需要明确指出参数的类型,正因为这样松散的约定,所以比较推荐的做法就是:

    靠开发来保证参数的类型说明,否则后续很难阅读。

    形式3:其中一个参数是有默认值的

    #return a * b
    #a: int | float
    #b: int | float
    def multiplyByDefault10(a, b = 10):
        return a * b
    
    t = multiplyByDefault10(100)
    print(t)

    输出结果:1000

    高级主题4:参数是引用传递还是值传递

    参考问题:https://www.zhihu.com/question/20591688

    所有函数都是引用传递,只是对于不可变类型的变量(int,float,string),会重新开辟一个空间;对于可变类型(dict,list等),是直接引用传递,操作数据时直接修改的原始变量。

    这点和c,php是不一样的,c可以传递指针,php可以传递引用,强制修改外部变量。

    高级主题5:可变参数的函数如何定义,如何使用?

    5.1,参数列表为tuple类型,只有value,没有key

    def print_changeable_args(*args):
        print(args)
    
    print_changeable_args(1, 2, 3)

    输出结果:

    (1, 2, 3)

    如果调用处改为:print_changeable_args(a=1, b=2, c=3)

    会报错:TypeError: print_changeable_args() got an unexpected keyword argument 'a'

    5.2,参数列表为dict类型,有key,也有value

    def print_changeable_args_dict(**args):
        print(args)
    
    print_changeable_args_dict(a=1, b=2)

    输出结果:

    {'a': 1, 'b': 2}

    如果调用处改为tuple方式:print_changeable_args_dict(1, 2)

    报错:TypeError: print_changeable_args_dict() takes 0 positional arguments but 2 were given

    5.3,不定参数中既有tuple,又有dict类型

    实际中很少出现这种情况,通常dict类型就可以搞定所有的情况。

    def print_changeable_tuple_dict(* argv1, ** argv2):
        print(argv1)
        print(argv2)
    
    print_changeable_tuple_dict(1, 2, 3)
    print_changeable_tuple_dict(1, 2, 3, a=1, b=2)

    输出:

    (1, 2, 3)
    {}
    (1, 2, 3)
    {'b': 2, 'a': 1}

    以上是正常情况。

    异常1:如果最开始没有tuple参数,直接使用dict参数,结果如何?

    print_changeable_tuple_dict(a=1, b=2)

    输出:

    ()
    {'b': 2, 'a': 1}

    异常2:如果tuple没有,dict也没有,结果如何?

    print_changeable_tuple_dict()
    输出:
    ()
    {}

    异常3:如果tuple有,dict也有,但是他们是乱序的。

    print_changeable_tuple_dict(a=1, 1)
    报错:SyntaxError: positional argument follows keyword argument
    
    
    print_changeable_tuple_dict(1, 2, 3, a=1, b=2, c=3, 4) 
    报错:SyntaxError: positional argument follows keyword argument

    可以看到tuple不能出现在dict后面。

    5.3,不定参数中既有tuple,又有dict类型,但是参数定义时dict在前,tuple在后

    def print_changeable_dict_tuple(**argv1, *argv2):
        print(argv1)
        print(argv2)
    
    print_changeable_dict_tuple(a=1)

    报错:

        def print_changeable_dict_tuple(**argv1, *argv2):
                                               ^
    SyntaxError: invalid syntax

     6,作为包函数来被其它文件所使用

    a,我们来构造一个函数

    #!/bin/python
    #!--encoding: UTF-8
    
    #fname(string): write file name
    #content(string): write content to fname
    def write_sth_to_file(fname, content):
        fp = open(fname, 'a+')
        fp.write(content + "
    ")
        fp.close()

    保存为helper.py。

    b,创建函数调用者example.py,这里必须和helper.py放在同一文件夹下

    #!/bin/python
    
    import helper
    
    helper.write_sth_to_file('/tmp/aaa.log', 'This is example')

    我们使用到a中的函数write_sth_to_file。

    执行结果就是把字符串附加到文件/tmp/aaa.log中。

    这里函数作为包中的一个单元被引入到其它文件中,是将来组建大型项目中必备的机制。

    这里有个疑问点需要解释下?为什么可以直接import helper就可以用呢?引用其它的包可以吗?这里引入的规则是什么?

    import查找包的逻辑是:

    a,优先加载和执行文件同一目录下的库,(example.py下如果有helper.py,则优先加载该文件,如果没有则继续查找);

    b,加载python的内置库(我本地是/usr/lib/python3.5/helper.py,如果没找到,则继续查找);

    c,加载python的个人local目录下的三方库(我本地是.local/lib/python3.5/site-packages/helper.py);

    d,加载python的三方包(我本地是/usr/local/lib/python3.5/dist-packages/helper.py);

  • 相关阅读:
    LeetCode Path Sum II
    LeetCode Longest Palindromic Substring
    LeetCode Populating Next Right Pointers in Each Node II
    LeetCode Best Time to Buy and Sell Stock III
    LeetCode Binary Tree Maximum Path Sum
    LeetCode Find Peak Element
    LeetCode Maximum Product Subarray
    LeetCode Intersection of Two Linked Lists
    一天一个设计模式(1)——工厂模式
    PHP迭代器 Iterator
  • 原文地址:https://www.cnblogs.com/helww/p/9831813.html
Copyright © 2020-2023  润新知