首页 > 编程语言 > 详细

Python3学习(2)-中级片

时间:2015-07-31 21:33:04      阅读:259      评论:0      收藏:0      [点我收藏+]

 

 


 

  • 切片:取数组、元组中的部分元素
    •  L=[Jack,Mick,Leon,Jane,Aiden]
    • 取前三个:使用索引
      • 技术分享
    • 取2-4个元素:索引
      • 技术分享
    • 取最后2个元素:索引,倒序
      • 技术分享
    • 取前3个元素:索引
      • 技术分享
  • N=[0,1,2,3,4,5,6,7,8,9]
    • 前8个中每2个取1个
      • 技术分享
    • 每3个中取1个
      • 技术分享
  • 高阶函数:map/reduce/filter/sorted
    • map:map()函数接收两个参数,一个是函数,一个是Iterablemap将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
      • >>> def f(x):
        ...     return x*x
        ...
        >>> r = map(f,[0,1,2,3,4,5,6,7,8,9])
        >>> list(r)
        [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    • reduce:reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
    • >>> from functools import reduce
      >>> def add(x,y):
      ...     return x+y
      ...
      >>> reduce(add,[1,3,5,7,9])
      25
    • filter:filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
    • >>> def is_odd(n):
      ...     return n % 2 == 1
      ...
      >>> list(filter(is_odd,[1,2,4,5,6,9,10,15]))
      [1, 5, 9, 15]
    • sorted:接收一个key函数来实现自定义的排序,例如按绝对值大小排序
    • >>> sorted([36,5,-12,9,-21],key=abs)    #按abs的结果升序排列
      [5, 9, -12, -21, 36]
      >>> sorted([BOB,aBOUT,zoo,Credit])    #按首字母的ASICC码
      [BOB, Credit, aBOUT, zoo]
  • 匿名函数
    • 关键字lambda表示匿名函数,冒号前面的x表示函数参数
    • 只能有一个表达式,不用写return,返回值就是该表达式的结果
    • >>> f = lambda x:x*x
      >>> f(5)
      25
  • 面向对象
    • 对象
      • 万物皆为对象
      • 所有事物均可封装为对象
    •  1 #定义一个Student的对象
       2 class Student(Object):
       3     #初始化对象的属性
       4     def __init__(self,name,score):
       5         self.name = name
       6         self.score = score
       7 
       8     #定义一个对象的方法print_score    
       9     def print_score(self):
      10         print(%s: %s%(self.name,self.score))
    • 访问限制
      • 属性前加‘__‘(双下划线)表示私有的属性,仅可内部访问,外部无法访问
      •  1 #定义一个Student的对象
         2 class Student(Object):
         3     #初始化对象的属性
         4     def __init__(self,name,score):
         5         #私有属性
         6         self.__name = name
         7         self.__score = score
         8 
         9     #定义一个对象的函数print_score    
        10     def print_score(self):
        11         print(%s: %s%(self.__name,self.__score))
    • 继承和多态
      • 继承:儿子会直接继承父亲的属性
      • 多态:可重写父类的方法
    •  获取对象信息
      • type(Object):输出对象的类型。
        • >>> a=AAA
          >>> type(a)
          <class str>
      • isinstance(Object,Type):判断对象的类型
        • >>> isinstance(a,str)
          True
          >>> isinstance(123,int)
          True
          >>> isinstance(123,str)
          False
      •  dir(Object):显示对象的所有属性和方法
        • >>> dir(a)
          [__add__, __class__, __contains__, __delattr__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __getitem__, __getnewargs__, __gt__, __hash__, __init__, __iter__, __le__, __len__, __lt__, __mod__, __mul__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __rmod__, __rmul__, __setattr__, __sizeof__, __str__, __subclasshook__, capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, maketrans, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill]
      • 实例属性和类方法
        • >>> class Student(object):
          ...     name = Student
          ...
          >>> s = Student()
          >>> print(s.name)
          Student
          >>> print(Student.name)
          Student
          >>> s.name = Jack
          >>> print(s.name)
          Jack
          >>> print(Student.name)
          Student
  • 单元测试
    • 用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。
    • 被测试模块mydict.py
      •  1 class Dict(dict):
         2 
         3     def __init__(self,**kw):
         4         super().__init__(**kw)
         5 
         6 
         7     def __getattr__(self,key):
         8         try:
         9             return self[key]
        10         except KeyError:
        11             raise AttributeError(r"‘Dict‘ object has no attribute %s" %key)
        12 
        13     def __setattr__(self,key,value):
        14         self[key] = value
    • 测试模块TestDict.py
      •  1 import unittest
         2 
         3 from mydict import Dict
         4 
         5 class TestDict(unittest.TestCase):
         6 
         7     def test_init(self):
         8         #完成数据初始化
         9         d = Dict(a=1,b=test)
        10         #判断d.a是否为1,为1则PASS,否则FAIL
        11         self.assertEqual(d.a,1)
        12         #判断d.b是否为‘test‘
        13         self.assertEqual(d.b,test)
        14         self.assertTrue(isinstance(d,dict))
        15 
        16 
        17 
        18 if __name__ == __main__:
        19     unittest.main()
    • 执行及结果:仅测试一个方法test_init(),且执行通过
      • ?  Python  python3 TestDict.py
        .
        ----------------------------------------------------------------------
        Ran 1 test in 0.000s
        
        OK
    • 说明
      • 测试模块需要继承unittest.TestCase
      • 测试方法命名需要以test开头
      • 使用断言来测试结果
      • setUp():在测试模块执行前,执行的方法
      • tearDown():在测试模块执行结束后,执行的方法

Python3学习(2)-中级片

原文:http://www.cnblogs.com/s380774061/p/4690916.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!