python学习-第8课

一、函数的命名规则

函数命名时,由多个单词拼接时,函数首字母小写,从第二个单词开始,首字母为大写,即函数命名为驼峰样式
def hello():
    print("hello world")
    
def newHello():
    print("this is new hello world")


二、装饰器

装饰器接收一个功能,添加一些功能并返回。

2.1.准备知识

Python中的一切(是的,甚至是类)都是对象。 我们定义的名称只是绑定到这些对象的标识符。 函数也不例外,它们也是对象(带有属性)。 各种不同的名称可以绑定到同一个功能对象。
示例1:
def first(msg):

    print(msg)
first("hello python")

second=first
second("this is python")

third=first("python test")
其中:
second和first一样,是提供相同输出的方法,名称first和second引用相同的函数对象。
third只是接受了first返回结果值

示例2:
#加法
def add(x):
    return x+1
#减法
def sub(x):
    return x-1
#操作函数
def operate(func,x):
    result=func(x)
    return result
#调用operate函数
print(operate(add,3))
print(operate(sub,7))

示例3:
此外,一个函数可以返回另一个函数
def backfunc():
    def returnfunc():
        print("Hello")
    return returnfunc
testfunc=backfunc()
testfunc()

2.2.装饰器

装饰器接收一个函数,添加一些函数并返回。 一般装饰器使用任何数量的参数,在Python中,这个由function(* args,** kwargs)完成。 这样,args将是位置参数的元组,kwargs将是关键字参数的字典。
示例1:
def startEnd(fun):
    def wraper():
        print("!!!!!!!!start!!!!!!!!")
        fun()
        print("!!!!!!!!!end!!!!!!!!!")
    return wraper
# hello()  相当于执行  wraper()
@startEnd
def hello():
    print("hello python")

hello()
装饰器通@进行使用,相当于把函数hello()作为参数传给startEnd()
@startEnd相当于hello=startEnd(hello)
调用hello()时,相当于调用了startEnd(hello)()

示例2:
#被除数校验
def check(func):
    def inner(a, b):
        print("除数是{0},被除数是{1}".format(a, b))
        if b == 0:
            print("被除数不能为0")
            return
        return func(a,b)
    return inner

@check
def divide(a, b):
    print("a除以b的商为{0}".format(a / b))

divide(6, 3)
divide(5, 0)

示例3:
#多个装饰器,一个函数可以用不同(或相同)装饰器多次装饰。
def type_one(func):
    def test01(*args,**kwargs):
        print("*"*30)
        func(*args,**kwargs)
        print("*"*30)
    return test01

def type_two(func):
    def test02(*args,**kwargs):
        print("#" * 30)
        func(*args, **kwargs)
        print("#" * 30)
    return test02

@type_one
@type_two
def printer(msg):
    print(msg)
printer(dict(a=1,b=2,c=3))
printer("my best day")

猜你喜欢

转载自blog.csdn.net/biankm_gz/article/details/79988516