zoukankan      html  css  js  c++  java
  • python基础(4)-----函数/装饰器

     函数

    在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。

    函数的优点之一是,可以将代码块与主程序分离。

    1、定义一个简单函数

    def greet_user():
        """这是一个函数的描述"""
        print("hello word")
    greet_user()

    2、向函数传递信息

    在函数greet_user()的定义中,变量username是一个形参,在代码greet_user("ljy")中,值"ljy"是一个实参,实参是调用函数时,传递给函数的信息。

    def greet_user(username):
        """这是一个函数的描述"""
        print("hello word",username)
    greet_user("ljy")

    3、函数与模块

    首先定义一个名为instance的模块

    def hello(name):
        'desc'
        print('hello,word',name+ '!')
    
    def buy(something):
        'desc'
        print('i want to buy',something + '!')
    

    导入整个模块并调用函数:

    import  instance
    instance.hello('ljy')
    instance.buy('car')
    #这个时候两个函数都是能够调用的
    

    导入特定的函数:

    from instance import hello
    hello('ljy')   #由于我们在import语句中已经指定了函数,所以此处不写模块名

     修饰器

    不修改函数源码的基础上修改函数-装饰器

    装饰器本质上是一个函数,该函数用来处理其他函数,它可以让其他函数在不需要修改代码的前提下增加额外的功能,装饰器的返回值也是一个函数对象。

    import  time
    def timer(func):
        start_time = time.time()
        func()  #run test1 运行函数
        stop_time = time.time()
        print("the fuction run time is %s" %(stop_time-start_time))
    
    @timer   #test1=timer(test1)  修饰器执行语法
    def test1():
        time.sleep(3)
        print("#################")
    
    @timer
    def test2():
        time.sleep(2)
        print("#################")
        
    test1 #修饰后的函数不用加()
    test2
    
  • 相关阅读:
    Leetcode95. Unique Binary Search Trees II不同的二叉搜索树2
    Leetcode134. Gas Station加油站
    Leetcode152. Maximum Product Subarray乘积的最大子序列
    C#扩展方法
    Lua语言入门
    Docker命令
    SpringBoot-配置文件属性注入-3种方式
    从零开始学Linux系统(五)用户管理和权限管理
    MyCat学习笔记
    kafka-zk-安装测试初体验
  • 原文地址:https://www.cnblogs.com/jinyuanliu/p/10341622.html
Copyright © 2011-2022 走看看