Python随堂(__slots__, modifier)

2017-07-11  本文已影响7人  Captain_tu

2017.7.10

  1. slots可以控制类不能新添加或者删除属性
    class slots:
    slots = {"x", "y"}
    def init(self, x, y):
    self.x = x
    self.y = y

     class notslots:
         def __init__(self, x, y):
             self.x = x
             self.y = y
    
     s1 = slots(10, 20)
     s1.m = 2    #AttributeError: 'slots' object has no attribute 'm'
     s2 = notslots(10, 20)
     s2.m = 2    #right
    
  2. modifier
    修饰器函数,可以对方法有限定的作用,修饰器函数只接受一个参数,即function
    def modifier(function):
    def wraper(*args, *kargs):
    result = function(
    args, **kargs)
    assert result > 0, "result must bigger than zero"
    return result

         wraper.__name__ = function.__name__
         wraper.__doc__ = function.__doc__
    
         return wraper
    
     @modifier
     def test_func(a, b):
     """
     this is a function count a - b
     when a is smaller than b, raise an exception
    
     for example: test_func(3, 1) => 2
     test_func(3, 4) =>  AssertionError
     """
         return a - b
    
  3. modifier2 修饰器函数还以有多个参数
    def modifier2(min_num, max_num):
    def out_wraper(function):
    def wraper(*args, *kargs):
    result = function(
    args, **kargs)

                 if result < min_num:
                     return min_num
                 elif result > max_num:
                     return max_num
                 else:
                     return result
    
             wraper.__name__ = function.__name__
             wraper.__doc__ = function.__doc__
    
             return wraper
    
       return out_wraper
    
     @modifier2(10, 100)
     def test_func2(a, b):
         return (a ** 3) / b - b
    
  4. with
    上下文环境
    with open("D://python/x.txt", "r") as fs:
    for line in fs:
    print(line)

     #可同时多个上下文环境
     with open("D://python/in.txt", "r") as fin, open("D://python/out.txt", "wa") as fout:
         for line fin:
             fout.write(line)
    
     #自定义上下文环境,需实现__enter__(self), __exit__(self, exc_type, exc_val, exc_tb)方法
     #在使用with时,__enter__会被调用,
     #当到达with末尾时,__exit__会被调用,如果没有异常发生,exc_type为None
    
  5. 函数性程序设计
    #map, filter, reduce(降低)
    lst = [1,2,3,4,5,6,7,8,9]
    map_lst = list(map(lambda x: x**2, lst))
    filter_lst = list(filter(lambda x: x%2==0, lst))

     #均可以用生成器表达式代替
     map_lst2 = [x**2 for x in lst]
     filter_lst = [x for x in lst if x % 2 == 0]
    
     #reduce_lst
     import functools
     functools.reduce(operator.mul, lst)
     functools.reduce(lambda x,y: x*y, lst)
上一篇下一篇

猜你喜欢

热点阅读