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
原文地址:https://www.cnblogs.com/jinyuanliu/p/10341622.html