参数传递、闭包、装饰器

一、参数传递

#包裹位置传递
def func(*name):
    print( type(name), name)
func(1,4,6)
func(5,6,7,1,2,3)
'''
运行结果:
<class 'tuple'> (1, 4, 6)
<class 'tuple'> (5, 6, 7, 1, 2, 3)
'''
#包裹关键字传递
def func(**dict):
    print( type(dict), dict)
func(a=1,b=9)
func(m=2,n=1,c=11)
'''
运行结果:
<class 'dict'> {'a': 1, 'b': 9}
<class 'dict'> {'m': 2, 'n': 1, 'c': 11}
'''

参考来源:http://www.cnblogs.com/vamei/archive/2012/07/08/2581264.html

二、闭包

def line_conf(a):
        b=1
        def line(x):
            return a * x + b
        return line
 
line_A = line_conf(2)
b=20
print(line_A(1))

line_A对象作为line_conf返回的闭包对象,它引用了line_conf下的变量b=1,即便后面全局作用域下定义了新的b变量指向20,最终结果仍然引用的line_conf内的b。

这是因为,闭包作为对象被返回时,它的引用变量就已经确定,不会再被修改

当然,闭包的参数例外。

def who(name):
    def do(what):
        print(name, 'say:', what)
    return do

lucy = who('lucy')
john = who('john')

lucy('i want drink!')
lucy('i want eat !')
lucy('i want play !')

john('i want play basketball')
john('i want to sleep with U,do U?')

lucy("you just like a fool, but i got you!")
'''
运行结果
lucy say: i want drink!
lucy say: i want eat !
lucy say: i want play !
john say: i want play basketball
john say: i want to sleep with U,do U?
lucy say: you just like a fool, but i got you!
'''

参考来源:https://blog.csdn.net/sc_lilei/article/details/80464645

三、装饰器

def decorator(F):
    def new_F(a, b):
        print("input", a, b)
        return F(a, b)
    return new_F

@decorator
def square_sum(a, b):
    return a**2 + b**2

@decorator
def square_diff(a, b):
    return a**2 - b**2

print(square_sum(3, 4))
print(square_diff(5, 6))

调用square_sum(3, 4)的时候,就相当于:

square_sum = decorator(square_sum)
square_sum(3, 4)

Python中的变量名和对象是分离的,变量名可以指向任意一个对象。

从本质上,装饰器起到的就是这样一个重新指向变量名的作用,让同一个变量名指向一个新返回的可调用对象,从而达到修改可调用对象的目的

如果我们有其他的类似函数,我们可以继续调用decorator来修饰函数,而不用重复修改函数或者增加新的封装。这样,我们就提高了程序的可重复利用性,并增加了程序的可读性。

常用的装饰器:

1、@unittest.skip('跳过')

2、@unittest.skipIf(3>2,'当条件为TRUE跳过')

3、@unittest.skipUnless(3>2,'当条件为TRUE时执行测试')

4、@unittest.expectedFailure  #不管执行是否失败统一标记为失败

5、@property  #获得属性、修改属性

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.__score = score

    #将 score变为一个只读的属性,同时可以通过数据属性的方式调用
    @property  
    def score(self):
        return self.__score

    #可以将 score变为一个有条件修改的属性
    @score.setter
    def score(self, score):
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self.__score = score    

想了解更多,查看参考来源:http://www.cnblogs.com/vamei/archive/2013/02/16/2820212.html

原文地址:https://www.cnblogs.com/yinwenbin/p/10547058.html