• Python函数:2018-07-30


    1. 关键字参数:使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值
    # -*- coding: UTF-8 -*-
    def printinfo(name, age = 22):
        print 'Name:',name
        print 'Age:',age
        return
    
    printinfo(age=50,name='Tom')
    printinfo(name='Jack')              
    

    输出:

    helloworld@LG-virtual-machine:~/code$ python test.py 
    Name: Tom
    Age: 50
    Name: Jack
    Age: 22
    
    1. 不定长参数:加了星号(*)的变量名会存放所有未命名的变量参数
    def functionname([formal_args,] *var_args_tuple ):
       function_suite
       return [expression]
    
    # -*- coding: UTF-8 -*-
    def printinfo(arg1, *varTuple):
        print "arg1:",arg1
        print "varTuple:",varTuple
        for var in varTuple:                                         
            print var
        return
    
    printinfo(10)
    printinfo(10,20,30,40,50)
    
    helloworld@LG-virtual-machine:~/code$ python test.py 
    arg1: 10
    varTuple: ()
    arg1: 10
    varTuple: (20, 30, 40, 50)
    20
    30
    40
    50
    
    1. 匿名函数:python使用lambda来构建匿名函数

    lambda [arg1 [,arg2,.....argn]]:expression

    # -*- coding: UTF-8 -*-                                          
    sum = lambda arg1,arg2:arg1+arg2
    
    print sum(10,20)
    print sum(1,7)
    

    输出:

    30
    8
    
    1. Python假设任何在函数内赋值的变量都是局部的。
      因此,如果要给函数内的全局变量赋值,必须使用 global 语句
    # -*- coding: UTF-8 -*-
    Money = 2000
    def addMoney():
        global Money
        Money += 1
    
    print Money
    addMoney()
    print Money                           
    

    输出:

    helloworld@LG-virtual-machine:~/code$ python test.py 
    2000
    2001
    
    1. dir():返回的列表容纳了在一个模块里定义的所有模块,变量和函数
    # -*- coding: UTF-8 -*-                                          
    import math
    
    content = dir(math)
    print content
    

    输出:

    ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
    'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
    'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
    'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
    'sqrt', 'tan', 'tanh']
    
    • 在这里,特殊字符串变量__name__指向模块的名字,__file__指向该模块的导入文件名
  • 相关阅读:
    清除浮动的三种方式
    js控制滚动条默认在底部
    npm 基础命令
    package.json中^,~的区别
    mac 使用iTerm2快捷登录远程服务器
    iterm 分屏切换快捷键与配色设置
    git tag — 标签相关操作
    gulp iconfont
    webpack 3 升级 webpack4 个人笔记
    import * as x from 'xx' 和 import x from 'xx'
  • 原文地址:https://www.cnblogs.com/qiulinzhang/p/9513589.html
Copyright © 2020-2023  润新知