Python Syntax Summary

   1 # _*_ coding: utf-8 _*_
   2 
   3 """################################################################################"""
   4 
   5 #-- 寻求帮助:
   6     dir(obj)            # 简单的列出对象obj所包含的方法名称,返回一个字符串列表
   7     help(obj.func)      # 查询obj.func的具体介绍和用法
   8     
   9 #-- 测试类型的三种方法,推荐第三种
  10 
  11     if type(L) == type([]):
  12         print("L is list")
  13     if type(L) == list:
  14         print("L is list")
  15     if isinstance(L, list):
  16         print("L is list")
  17         
  18 #-- Python数据类型:哈希类型、不可哈希类型
  19 
  20     # 哈希类型,即在原地不能改变的变量类型,不可变类型。可利用hash函数查看其hash值,也可以作为字典的key
  21     "数字类型:int, float, decimal.Decimal, fractions.Fraction, complex"
  22     "字符串类型:str, bytes"
  23     "元组:tuple"
  24     "冻结集合:frozenset"
  25     "布尔类型:True, False"
  26     "None"
  27     # 不可hash类型:原地可变类型:list、dict和set。它们不可以作为字典的key。
  28 
  29 #-- 数字常量
  30 
  31     1234, -1234, 0, 999999999                    # 整数
  32     1.23, 1., 3.14e-10, 4E210, 4.0e+210          # 浮点数
  33     0o177, 0x9ff, 0X9FF, 0b101010                # 八进制、十六进制、二进制数字
  34     3+4j, 3.0+4.0j, 3J                           # 复数常量,也可以用complex(real, image)来创建
  35     hex(I), oct(I), bin(I)                       # 将十进制数转化为十六进制、八进制、二进制表示的“字符串”
  36     int(string, base)                            # 将字符串转化为整数,base为进制数
  37     # 2.x中,有两种整数类型:一般整数(32位)和长整数(无穷精度)。可以用l或L结尾,迫使一般整数成为长整数
  38     float('inf'), float('-inf'), float('nan')    # 无穷大, 无穷小, 非数
  39     
  40 #-- 数字的表达式操作符
  41 
  42     yield x                                      # 生成器函数发送协议
  43     lambda args: expression                      # 生成匿名函数
  44     x if y else z                                # 三元选择表达式
  45     x and y, x or y, not x                       # 逻辑与、逻辑或、逻辑非
  46     x in y, x not in y                           # 成员对象测试
  47     x is y, x is not y                           # 对象实体测试
  48     x<y, x<=y, x>y, x>=y, x==y, x!=y             # 大小比较,集合子集或超集值相等性操作符
  49     1 < a < 3                                    # Python中允许连续比较
  50     x|y, x&y, x^y                                # 位或、位与、位异或
  51     x<<y, x>>y                                   # 位操作:x左移、右移y位
  52     +, -, *, /, //, %, **                        # 真除法、floor除法:返回不大于真除法结果的整数值、取余、幂运算
  53     -x, +x, ~x                                   # 一元减法、识别、按位求补(取反)
  54     x[i], x[i:j:k]                               # 索引、分片
  55     int(3.14), float(3)                          # 强制类型转换
  56     
  57 #-- 整数可以利用bit_length函数测试所占的位数
  58 
  59     a = 1;       a.bit_length()    # 1
  60     a = 1024;    a.bit_length()    # 11
  61     
  62 #-- repr和str显示格式的区别
  63     """
  64     repr格式:默认的交互模式回显,产生的结果看起来它们就像是代码。
  65     str格式:打印语句,转化成一种对用户更加友好的格式。
  66     """
  67     
  68 #-- 数字相关的模块
  69     # math模块
  70     # Decimal模块:小数模块
  71         import decimal
  72         from decimal import Decimal
  73         Decimal("0.01") + Decimal("0.02")        # 返回Decimal("0.03")
  74         decimal.getcontext().prec = 4            # 设置全局精度为4 即小数点后边4位
  75     # Fraction模块:分数模块
  76         from fractions import Fraction
  77         x = Fraction(4, 6)                       # 分数类型 4/6
  78         x = Fraction("0.25")                     # 分数类型 1/4 接收字符串类型的参数
  79 
  80 #-- 集合set
  81     """
  82     set是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素。
  83     set支持union(联合), intersection(交), difference(差)和symmetric difference(对称差集)等数学运算。
  84     set支持x in set, len(set), for x in set。
  85     set不记录元素位置或者插入点, 因此不支持indexing, slicing, 或其它类序列的操作
  86     """
  87     s = set([3,5,9,10])                          # 创建一个数值集合,返回{3, 5, 9, 10}
  88     t = set("Hello")                             # 创建一个字符的集合,返回{'l', 'H', 'e', 'o'}
  89     a = t | s;    t.union(s)                     # t 和 s的并集
  90     b = t & s;    t.intersection(s)              # t 和 s的交集
  91     c = t – s;    t.difference(s)                # 求差集(项在t中, 但不在s中)
  92     d = t ^ s;    t.symmetric_difference(s)      # 对称差集(项在t或s中, 但不会同时出现在二者中)
  93     t.add('x');   t.remove('H')                  # 增加/删除一个item
  94     s.update([10,37,42])                         # 利用[......]更新s集合
  95     x in s,  x not in s                          # 集合中是否存在某个值
  96     s.issubset(t);      s <= t                   # 测试是否 s 中的每一个元素都在 t 中
  97     s.issuperset(t);    s >= t                   # 测试是否 t 中的每一个元素都在 s 中 
  98     s.copy(); 
  99     s.discard(x);                                # 删除s中x
 100     s.clear()                                    # 清空s
 101     {x**2 for x in [1, 2, 3, 4]}                 # 集合解析,结果:{16, 1, 4, 9}
 102     {x for x in 'spam'}                          # 集合解析,结果:{'a', 'p', 's', 'm'}
 103     
 104 #-- 集合frozenset,不可变对象
 105     """
 106     set是可变对象,即不存在hash值,不能作为字典的键值。同样的还有list等(tuple是可以作为字典key的)
 107     frozenset是不可变对象,即存在hash值,可作为字典的键值
 108     frozenset对象没有add、remove等方法,但有union/intersection/difference等方法
 109     """
 110     a = set([1, 2, 3])
 111     b = set()
 112     b.add(a)                     # error: set是不可哈希类型
 113     b.add(frozenset(a))          # ok,将set变为frozenset,可哈希
 114 
 115 #-- 布尔类型bool
 116     type(True)                   # 返回<class 'bool'>
 117     isinstance(False, int)       # bool类型属于整型,所以返回True
 118     True == 1; True is 1         # 输出(True, False)
 119     
 120 #-- 动态类型简介
 121     """
 122     变量名通过引用,指向对象。
 123     Python中的“类型”属于对象,而不是变量,每个对象都包含有头部信息,比如"类型标示符" "引用计数器"等
 124     """
 125     #共享引用及在原处修改:对于可变对象,要注意尽量不要共享引用!
 126     #共享引用和相等测试:
 127         L = [1], M = [1], L is M            # 返回False
 128         L = M = [1, 2, 3], L is M           # 返回True,共享引用
 129     #增强赋值和共享引用:普通+号会生成新的对象,而增强赋值+=会在原处修改
 130         L = M = [1, 2]
 131         L = L + [3, 4]                      # L = [1, 2, 3, 4], M = [1, 2]
 132         L += [3, 4]                         # L = [1, 2, 3, 4], M = [1, 2, 3, 4]
 133 
 134 #-- 常见字符串常量和表达式
 135     S = ''                                  # 空字符串
 136     S = "spam’s"                            # 双引号和单引号相同
 137     S = "s\np\ta\x00m"                      # 转义字符
 138     S = """spam"""                          # 三重引号字符串,一般用于函数说明
 139     S = r'\temp'                            # Raw字符串,不会进行转义,抑制转义
 140     S = b'Spam'                             # Python3中的字节字符串
 141     S = u'spam'                             # Python2.6中的Unicode字符串
 142     s1+s2, s1*3, s[i], s[i:j], len(s)       # 字符串操作
 143     'a %s parrot' % 'kind'                  # 字符串格式化表达式
 144     'a {1} {0} parrot'.format('kind', 'red')# 字符串格式化方法
 145     for x in s: print(x)                    # 字符串迭代,成员关系
 146     [x*2 for x in s]                        # 字符串列表解析
 147     ','.join(['a', 'b', 'c'])               # 字符串输出,结果:a,b,c
 148     
 149 #-- 内置str处理函数:
 150     str1 = "stringobject"
 151     str1.upper(); str1.lower(); str1.swapcase(); str1.capitalize(); str1.title()        # 全部大写,全部小写、大小写转换,首字母大写,每个单词的首字母都大写
 152     str1.ljust(width)                       # 获取固定长度,左对齐,右边不够用空格补齐
 153     str1.rjust(width)                       # 获取固定长度,右对齐,左边不够用空格补齐
 154     str1.center(width)                      # 获取固定长度,中间对齐,两边不够用空格补齐
 155     str1.zfill(width)                       # 获取固定长度,右对齐,左边不足用0补齐
 156     str1.find('t',start,end)                # 查找字符串,可以指定起始及结束位置搜索
 157     str1.rfind('t')                         # 从右边开始查找字符串
 158     str1.count('t')                         # 查找字符串出现的次数
 159     #上面所有方法都可用index代替,不同的是使用index查找不到会抛异常,而find返回-1
 160     str1.replace('old','new')               # 替换函数,替换old为new,参数中可以指定maxReplaceTimes,即替换指定次数的old为new
 161     str1.strip();                           # 默认删除空白符
 162     str1.strip('d');                        # 删除str1字符串中开头、结尾处,位于 d 删除序列的字符
 163     str1.lstrip();
 164     str1.lstrip('d');                       # 删除str1字符串中开头处,位于 d 删除序列的字符
 165     str1.rstrip();
 166     str1.rstrip('d')                        # 删除str1字符串中结尾处,位于 d 删除序列的字符
 167     str1.startswith('start')                # 是否以start开头
 168     str1.endswith('end')                    # 是否以end结尾
 169     str1.isalnum(); str1.isalpha(); str1.isdigit(); str1.islower(); str1.isupper()      # 判断字符串是否全为字符、数字、小写、大写
 170 
 171 #-- 三重引号编写多行字符串块,并且在代码折行处嵌入换行字符\n
 172     mantra = """hello world
 173             hello python
 174             hello my friend"""
 175     # mantra为"""hello world \n hello python \n hello my friend"""
 176     
 177 #-- 索引和分片:
 178     S[0], S[len(S)–1], S[-1]                # 索引
 179     S[1:3], S[1:], S[:-1], S[1:10:2]        # 分片,第三个参数指定步长,如`S[1:10:2]`是从1位到10位没隔2位获取一个字符。
 180 
 181 #-- 字符串转换工具:
 182     int('42'), str(42)                      # 返回(42, '42')
 183     float('4.13'), str(4.13)                # 返回(4.13, '4.13')
 184     ord('s'), chr(115)                      # 返回(115, 's')
 185     int('1001', 2)                          # 将字符串作为二进制数字,转化为数字,返回9
 186     bin(13), oct(13), hex(13)               # 将整数转化为二进制/八进制/十六进制字符串,返回('0b1101', '015', '0xd')
 187     
 188 #-- 另类字符串连接
 189     name = "wang" "hong"                    # 单行,name = "wanghong"
 190     name = "wang" \
 191             "hong"                          # 多行,name = "wanghong"
 192 
 193 #-- Python中的字符串格式化实现1--字符串格式化表达式
 194     """
 195     基于C语言的'print'模型,并且在大多数的现有的语言中使用。
 196     通用结构:%[(name)][flag][width].[precision]typecode
 197     """
 198     "this is %d %s bird" % (1, 'dead')                          # 一般的格式化表达式
 199     "%s---%s---%s" % (42, 3.14, [1, 2, 3])                      # 字符串输出:'42---3.14---[1, 2, 3]'
 200     "%d...%6d...%-6d...%06d" % (1234, 1234, 1234, 1234)         # 对齐方式及填充:"1234...  1234...1234  ...001234"
 201     x = 1.23456789
 202     "%e | %f | %g" % (x, x, x)                                  # 对齐方式:"1.234568e+00 | 1.234568 | 1.23457"
 203     "%6.2f*%-6.2f*%06.2f*%+6.2f" % (x, x, x, x)                 # 对齐方式:'  1.23*1.23  *001.23* +1.23'
 204     "%(name1)d---%(name2)s" % {"name1":23, "name2":"value2"}    # 基于字典的格式化表达式
 205     "%(name)s is %(age)d" % vars()                              # vars()函数调用返回一个字典,包含了所有本函数调用时存在的变量
 206     
 207 #-- Python中的字符串格式化实现2--字符串格式化调用方法
 208     # 普通调用
 209     "{0}, {1} and {2}".format('spam', 'ham', 'eggs')            # 基于位置的调用
 210     "{motto} and {pork}".format(motto = 'spam', pork = 'ham')   # 基于Key的调用
 211     "{motto} and {0}".format('ham', motto = 'spam')             # 混合调用
 212     # 添加键 属性 偏移量 (import sys)
 213     "my {1[spam]} runs {0.platform}".format(sys, {'spam':'laptop'})                 # 基于位置的键和属性
 214     "{config[spam]} {sys.platform}".format(sys = sys, config = {'spam':'laptop'})   # 基于Key的键和属性
 215     "first = {0[0]}, second = {0[1]}".format(['A', 'B', 'C'])                       # 基于位置的偏移量
 216     # 具体格式化
 217     "{0:e}, {1:.3e}, {2:g}".format(3.14159, 3.14159, 3.14159)   # 输出'3.141590e+00, 3.142e+00, 3.14159'
 218     "{fieldname:format_spec}".format(......)
 219     # 说明:
 220     """
 221         fieldname是指定参数的一个数字或关键字, 后边可跟可选的".name"或"[index]"成分引用
 222         format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
 223         fill        ::=  <any character>              #填充字符
 224         align       ::=  "<" | ">" | "=" | "^"        #对齐方式
 225         sign        ::=  "+" | "-" | " "              #符号说明
 226         width       ::=  integer                      #字符串宽度
 227         precision   ::=  integer                      #浮点数精度
 228         type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
 229     """
 230     # 例子:
 231         '={0:10} = {1:10}'.format('spam', 123.456)    # 输出'=spam       =    123.456'
 232         '={0:>10}='.format('test')                    # 输出'=      test='
 233         '={0:<10}='.format('test')                    # 输出'=test      ='
 234         '={0:^10}='.format('test')                    # 输出'=   test   ='
 235         '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)   # 输出'FF, 377, 11111111'
 236         'My name is {0:{1}}.'.format('Fred', 8)       # 输出'My name is Fred    .'  动态指定参数
 237 
 238 #-- 常用列表常量和操作
 239     L = [[1, 2], 'string', {}]                        # 嵌套列表
 240     L = list('spam')                                  # 列表初始化
 241     L = list(range(0, 4))                             # 列表初始化
 242     list(map(ord, 'spam'))                            # 列表解析
 243     len(L)                                            # 求列表长度
 244     L.count(value)                                    # 求列表中某个值的个数
 245     L.append(obj)                                     # 向列表的尾部添加数据,比如append(2),添加元素2
 246     L.insert(index, obj)                              # 向列表的指定index位置添加数据,index及其之后的数据后移
 247     L.extend(interable)                               # 通过添加iterable中的元素来扩展列表,比如extend([2]),添加元素2,注意和append的区别
 248     L.index(value, [start, [stop]])                   # 返回列表中值value的第一个索引
 249     L.pop([index])                                    # 删除并返回index处的元素,默认为删除并返回最后一个元素
 250     L.remove(value)                                   # 删除列表中的value值,只删除第一次出现的value的值
 251     L.reverse()                                       # 反转列表
 252     L.sort(cmp=None, key=None, reverse=False)         # 排序列表
 253     a = [1, 2, 3], b = a[10:]                         # 注意,这里不会引发IndexError异常,只会返回一个空的列表[]
 254     a = [], a += [1]                                  # 这里实在原有列表的基础上进行操作,即列表的id没有改变
 255     a = [], a = a + [1]                               # 这里最后的a要构建一个新的列表,即a的id发生了变化
 256      
 257 #-- 用切片来删除序列的某一段
 258     a = [1, 2, 3, 4, 5, 6, 7]
 259     a[1:4] = []                                       # a = [1, 5, 6, 7]
 260     a = [0, 1, 2, 3, 4, 5, 6, 7]
 261     del a[::2]                                        # 去除偶数项(偶数索引的),a = [1, 3, 5, 7]
 262     
 263 #-- 常用字典常量和操作
 264     D = {}
 265     D = {'spam':2, 'tol':{'ham':1}}                   # 嵌套字典
 266     D = dict.fromkeys(['s', 'd'], 8)                  # {'s': 8, 'd': 8}
 267     D = dict(name = 'tom', age = 12)                  # {'age': 12, 'name': 'tom'}
 268     D = dict([('name', 'tom'), ('age', 12)])          # {'age': 12, 'name': 'tom'}
 269     D = dict(zip(['name', 'age'], ['tom', 12]))       # {'age': 12, 'name': 'tom'}
 270     D.keys(); D.values(); D.items()                   # 字典键、值以及键值对
 271     D.get(key, default)                               # get函数
 272     D.update(D_other)                                 # 合并字典,如果存在相同的键值,D_other的数据会覆盖掉D的数据
 273     D.pop(key, [D])                                   # 删除字典中键值为key的项,返回键值为key的值,如果不存在,返回默认值D,否则异常
 274     D.popitem()                                       # pop字典中随机的一项(一个键值对)
 275     D.setdefault(k[, d])                              # 设置D中某一项的默认值。如果k存在,则返回D[k],否则设置D[k]=d,同时返回D[k]。
 276     del D                                             # 删除字典
 277     del D['key']                                      # 删除字典的某一项
 278     if key in D:   if key not in D:                   # 测试字典键是否存在
 279     # 字典注意事项:(1)对新索引赋值会添加一项(2)字典键不一定非得是字符串,也可以为任何的不可变对象
 280     # 不可变对象:调用对象自身的任意方法,也不会改变该对象自身的内容,这些方法会创建新的对象并返回。
 281     # 字符串、整数、tuple都是不可变对象,dict、set、list都是可变对象
 282     D[(1,2,3)] = 2                                    # tuple作为字典的key
 283 
 284 #-- 字典解析
 285     D = {k:8 for k in ['s', 'd']}                     # {'s': 8, 'd': 8}
 286     D = {k:v for (k, v) in zip(['name', 'age'], ['tom', 12])}       # {'age': 12, 'name': tom}
 287     
 288 #-- 字典的特殊方法__missing__:当查找找不到key时,会执行该方法
 289     class Dict(dict):
 290         def __missing__(self, key):
 291             self[key] = []
 292             return self[key]
 293     dct = dict()
 294     dct["foo"].append(1)    # 这有点类似于collections.defalutdict
 295     dct["foo"]              # [1]
 296     
 297 #-- 元组和列表的唯一区别在于元组是不可变对象,列表是可变对象
 298     a = [1, 2, 3]           # a[1] = 0, OK
 299     a = (1, 2, 3)           # a[1] = 0, Error
 300     a = ([1, 2])            # a[0][1] = 0, OK
 301     a = [(1, 2)]            # a[0][1] = 0, Error
 302     
 303 #-- 元组的特殊语法: 逗号和圆括号
 304     D = (12)                # 此时D为一个整数 即D = 12
 305     D = (12, )              # 此时D为一个元组 即D = (12, )
 306     
 307 #-- 文件基本操作
 308     output = open(r'C:\spam', 'w')          # 打开输出文件,用于写
 309     input = open('data', 'r')               # 打开输入文件,用于读。打开的方式可以为'w', 'r', 'a', 'wb', 'rb', 'ab'等
 310     fp.read([size])                         # size为读取的长度,以byte为单位
 311     fp.readline([size])                     # 读一行,如果定义了size,有可能返回的只是一行的一部分
 312     fp.readlines([size])                    # 把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长。
 313     fp.readable()                           # 是否可读
 314     fp.write(str)                           # 把str写到文件中,write()并不会在str后加上一个换行符
 315     fp.writelines(seq)                      # 把seq的内容全部写到文件中(多行一次性写入)
 316     fp.writeable()                          # 是否可写
 317     fp.close()                              # 关闭文件。
 318     fp.flush()                              # 把缓冲区的内容写入硬盘
 319     fp.fileno()                             # 返回一个长整型的”文件标签“
 320     fp.isatty()                             # 文件是否是一个终端设备文件(unix系统中的)
 321     fp.tell()                               # 返回文件操作标记的当前位置,以文件的开头为原点
 322     fp.next()                               # 返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。
 323     fp.seek(offset[,whence])                # 将文件打开操作标记移到offset的位置。whence为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。
 324     fp.seekable()                           # 是否可以seek
 325     fp.truncate([size])                     # 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。
 326     for line in open('data'): 
 327         print(line)                         # 使用for语句,比较适用于打开比较大的文件
 328     with open('data') as file:
 329         print(file.readline())              # 使用with语句,可以保证文件关闭
 330     with open('data') as file:
 331         lines = file.readlines()            # 一次读入文件所有行,并关闭文件
 332     open('f.txt', encoding = 'latin-1')     # Python3.x Unicode文本文件
 333     open('f.bin', 'rb')                     # Python3.x 二进制bytes文件
 334     # 文件对象还有相应的属性:buffer closed encoding errors line_buffering name newlines等
 335     
 336 #-- 其他
 337     # Python中的真假值含义:1. 数字如果非零,则为真,0为假。 2. 其他对象如果非空,则为真
 338     # 通常意义下的类型分类:1. 数字、序列、映射。 2. 可变类型和不可变类型
 339 
 340 
 341 """语法和语句----语法和语句----语法和语句----语法和语句----语法和语句----语法和语句----语法和语句----语法和语句----语法和语句----语法和语句----语法和语句"""
 342 
 343 #-- 赋值语句的形式
 344     spam = 'spam'                          # 基本形式
 345     spam, ham = 'spam', 'ham'              # 元组赋值形式
 346     [spam, ham] = ['s', 'h']               # 列表赋值形式
 347     a, b, c, d = 'abcd'                    # 序列赋值形式
 348     a, *b, c = 'spam'                      # 序列解包形式(Python3.x中才有)
 349     spam = ham = 'no'                      # 多目标赋值运算,涉及到共享引用
 350     spam += 42                             # 增强赋值,涉及到共享引用
 351 
 352 #-- 序列赋值 序列解包
 353     [a, b, c] = (1, 2, 3)                  # a = 1, b = 2, c = 3
 354     a, b, c, d = "spam"                    # a = 's', b = 'p', c = 'a', d = 'm'
 355     a, b, c = range(3)                     # a = 0, b = 1, c = 2
 356     a, *b = [1, 2, 3, 4]                   # a = 1, b = [2, 3, 4]
 357     *a, b = [1, 2, 3, 4]                   # a = [1, 2, 3], b = 4
 358     a, *b, c = [1, 2, 3, 4]                # a = 1, b = [2, 3], c = 4
 359     # 带有*时 会优先匹配*之外的变量 如
 360     a, *b, c = [1, 2]                      # a = 1, c = 2, b = []
 361 
 362 #-- print函数原型
 363     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
 364     # 流的重定向
 365     print('hello world')                   # 等于sys.stdout.write('hello world')
 366     temp = sys.stdout                      # 原有流的保存
 367     sys.stdout = open('log.log', 'a')      # 流的重定向
 368     print('hello world')                   # 写入到文件log.log
 369     sys.stdout.close()
 370     sys.stdout = temp                      # 原有流的复原
 371     
 372 #-- Python中and或or总是返回对象(左边的对象或右边的对象) 且具有短路求值的特性
 373     1 or 2 or 3                            # 返回 1
 374     1 and 2 and 3                          # 返回 3
 375 
 376 #-- if/else三元表达符(if语句在行内)
 377     A = 1 if X else 2
 378     A = 1 if X else (2 if Y else 3)
 379     # 也可以使用and-or语句(一条语句实现多个if-else)
 380     a = 6
 381     result = (a > 20 and "big than 20" or a > 10 and "big than 10" or a > 5 and "big than 5")    # 返回"big than 5"
 382 
 383 #-- Python的while语句或者for语句可以带else语句 当然也可以带continue/break/pass语句
 384     while a > 1:
 385         anything
 386     else:
 387         anything
 388     # else语句会在循环结束后执行,除非在循环中执行了break,同样的还有for语句
 389     for i in range(5):
 390         anything
 391     else:
 392         anything
 393 
 394 #-- for循环的元组赋值
 395     for (a, b) in [(1, 2), (3, 4)]:                   # 最简单的赋值
 396     for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]:    # 自动解包赋值
 397     for ((a, b), c) in [((1, 2), 3), ("XY", 6)]:      # 自动解包 a = X, b = Y, c = 6
 398     for (a, *b) in [(1, 2, 3), (4, 5, 6)]:            # 自动解包赋值
 399 
 400 #-- 列表解析语法
 401     M = [[1,2,3], [4,5,6], [7,8,9]]
 402     res = [sum(row) for row in M]                     # G = [6, 15, 24] 一般的列表解析 生成一个列表
 403     res = [c * 2 for c in 'spam']                     # ['ss', 'pp', 'aa', 'mm']
 404     res = [a * b for a in [1, 2] for b in [4, 5]]     # 多解析过程 返回[4, 5, 8, 10]
 405     res = [a for a in [1, 2, 3] if a < 2]             # 带判断条件的解析过程
 406     res = [a if a > 0 else 0 for a in [-1, 0, 1]]     # 带判断条件的高级解析过程
 407     # 两个列表同时解析:使用zip函数
 408     for teama, teamb in zip(["Packers", "49ers"], ["Ravens", "Patriots"]):
 409         print(teama + " vs. " + teamb)
 410     # 带索引的列表解析:使用enumerate函数
 411     for index, team in enumerate(["Packers", "49ers", "Ravens", "Patriots"]):
 412         print(index, team)                            # 输出0, Packers \n 1, 49ers \n ......
 413     
 414 #-- 生成器表达式
 415     G = (sum(row) for row in M)                       # 使用小括号可以创建所需结果的生成器generator object
 416     next(G), next(G), next(G)                         # 输出(6, 15, 24)
 417     G = {sum(row) for row in M}                       # G = {6, 15, 24} 解析语法还可以生成集合和字典
 418     G = {i:sum(M[i]) for i in range(3)}               # G = {0: 6, 1: 15, 2: 24}
 419 
 420 #-- 文档字符串:出现在Module的开端以及其中函数或类的开端 使用三重引号字符串
 421     """
 422     module document
 423     """
 424     def func():
 425         """
 426         function document
 427         """
 428         print()
 429     class Employee(object):
 430         """
 431         class document
 432         """
 433         print()
 434     print(func.__doc__)                # 输出函数文档字符串
 435     print(Employee.__doc__)            # 输出类的文档字符串
 436     
 437 #-- 命名惯例:
 438     """
 439     以单一下划线开头的变量名(_X)不会被from module import*等语句导入
 440     前后有两个下划线的变量名(__X__)是系统定义的变量名,对解释器有特殊意义
 441     以两个下划线开头但不以下划线结尾的变量名(__X)是类的本地(私有)变量
 442     """
 443 
 444 #-- 列表解析 in成员关系测试 map sorted zip enumerate内置函数等都使用了迭代协议
 445     'first line' in open('test.txt')   # in测试 返回True或False
 446     list(map(str.upper, open('t')))    # map内置函数
 447     sorted(iter([2, 5, 8, 3, 1]))      # sorted内置函数
 448     list(zip([1, 2], [3, 4]))          # zip内置函数 [(1, 3), (2, 4)]
 449 
 450 #-- del语句: 手动删除某个变量
 451     del X
 452 
 453 #-- 获取列表的子表的方法:
 454     x = [1,2,3,4,5,6]
 455     x[:3]                              # 前3个[1,2,3]
 456     x[1:5]                             # 中间4个[2,3,4,5]
 457     x[-3:]                             # 最后3个[4,5,6]
 458     x[::2]                             # 奇数项[1,3,5]
 459     x[1::2]                            # 偶数项[2,4,6]
 460     
 461 #-- 手动迭代:iter和next
 462     L = [1, 2]
 463     I = iter(L)                        # I为L的迭代器
 464     I.next()                           # 返回1
 465     I.next()                           # 返回2
 466     I.next()                           # Error:StopIteration
 467     
 468 #-- Python中的可迭代对象
 469     """
 470     1.range迭代器
 471     2.map、zip和filter迭代器
 472     3.字典视图迭代器:D.keys()), D.items()等
 473     4.文件类型
 474     """
 475 
 476 
 477 """函数语法规则----函数语法规则----函数语法规则----函数语法规则----函数语法规则----函数语法规则----函数语法规则----函数语法规则----函数语法规则----函数语法规则"""
 478 
 479 #-- 函数相关的语句和表达式
 480     myfunc('spam')                     # 函数调用
 481     def myfunc():                      # 函数定义
 482     return None                        # 函数返回值
 483     global a                           # 全局变量
 484     nonlocal x                         # 在函数或其他作用域中使用外层(非全局)变量
 485     yield x                            # 生成器函数返回
 486     lambda                             # 匿名函数
 487     
 488 #-- Python函数变量名解析:LEGB原则,即:
 489     """
 490     local(functin) --> encloseing function locals --> global(module) --> build-in(python)
 491     说明:以下边的函数maker为例 则相对于action而言 X为Local N为Encloseing
 492     """
 493 
 494 #-- 嵌套函数举例:工厂函数
 495     def maker(N):
 496         def action(X):
 497             return X ** N
 498         return action
 499     f = maker(2)                       # pass 2 to N
 500     f(3)                               # 9, pass 3 to X
 501 
 502 #-- 嵌套函数举例:lambda实例
 503     def maker(N):
 504         action = (lambda X: X**N)
 505         return action
 506     f = maker(2)                       # pass 2 to N
 507     f(3)                               # 9, pass 3 to X
 508 
 509 #-- nonlocal和global语句的区别
 510     # nonlocal应用于一个嵌套的函数的作用域中的一个名称 例如:
 511     start = 100
 512     def tester(start):
 513         def nested(label):
 514             nonlocal start             # 指定start为tester函数内的local变量 而不是global变量start
 515             print(label, start)
 516             start += 3
 517         return nested
 518     # global为全局的变量 即def之外的变量
 519     def tester(start):
 520         def nested(label):
 521             global start               # 指定start为global变量start
 522             print(label, start)
 523             start += 3
 524         return nested    
 525     
 526 #-- 函数参数,不可变参数通过“值”传递,可变参数通过“引用”传递
 527     def f(a, b, c): print(a, b, c)
 528     f(1, 2, 3)                         # 参数位置匹配
 529     f(1, c = 3, b = 2)                 # 参数关键字匹配
 530     def f(a, b=1, c=2): print(a, b, c)
 531     f(1)                               # 默认参数匹配
 532     f(1, 2)                            # 默认参数匹配
 533     f(a = 1, c = 3)                    # 关键字参数和默认参数的混合
 534     # Keyword-Only参数:出现在*args之后 必须用关键字进行匹配
 535     def keyOnly(a, *b, c): print('')   # c就为keyword-only匹配 必须使用关键字c = value匹配
 536     def keyOnly(a, *, b, c): ......    # b c为keyword-only匹配 必须使用关键字匹配
 537     def keyOnly(a, *, b = 1): ......   # b有默认值 或者省略 或者使用关键字参数b = value
 538 
 539 #-- 可变参数匹配: * 和 **
 540     def f(*args): print(args)          # 在元组中收集不匹配的位置参数
 541     f(1, 2, 3)                         # 输出(1, 2, 3)
 542     def f(**args): print(args)         # 在字典中收集不匹配的关键字参数
 543     f(a = 1, b = 2)                    # 输出{'a':1, 'b':2}
 544     def f(a, *b, **c): print(a, b, c)  # 两者混合使用
 545     f(1, 2, 3, x=4, y=5)               # 输出1, (2, 3), {'x':4, 'y':5}
 546     
 547 #-- 函数调用时的参数解包: * 和 ** 分别解包元组和字典
 548     func(1, *(2, 3))  <==>  func(1, 2, 3)
 549     func(1, **{'c':3, 'b':2})  <==>  func(1, b = 2, c = 3)
 550     func(1, *(2, 3), **{'c':3, 'b':2})  <==>  func(1, 2, 3, b = 2, c = 3)
 551     
 552 #-- 函数属性:(自己定义的)函数可以添加属性
 553     def func():.....
 554     func.count = 1                     # 自定义函数添加属性
 555     print.count = 1                    # Error 内置函数不可以添加属性
 556     
 557 #-- 函数注解: 编写在def头部行 主要用于说明参数范围、参数类型、返回值类型等
 558     def func(a:'spam', b:(1, 10), c:float) -> int :
 559         print(a, b, c)
 560     func.__annotations__               # {'c':<class 'float'>, 'b':(1, 10), 'a':'spam', 'return':<class 'int'>}
 561     # 编写注解的同时 还是可以使用函数默认值 并且注解的位置位于=号的前边
 562     def func(a:'spam'='a', b:(1, 10)=2, c:float=3) -> int :
 563         print(a, b, c)
 564 
 565 #-- 匿名函数:lambda
 566     f = lambda x, y, z : x + y + z     # 普通匿名函数,使用方法f(1, 2, 3)
 567     f = lambda x = 1, y = 1: x + y     # 带默认参数的lambda函数
 568     def action(x):                     # 嵌套lambda函数
 569         return (lambda y : x + y)
 570     f = lambda: a if xxx() else b      # 无参数的lambda函数,使用方法f()
 571 
 572 #-- lambda函数与map filter reduce函数的结合
 573     list(map((lambda x: x + 1), [1, 2, 3]))              # [2, 3, 4]
 574     list(filter((lambda x: x > 0), range(-4, 5)))        # [1, 2, 3, 4]
 575     functools.reduce((lambda x, y: x + y), [1, 2, 3])    # 6
 576     functools.reduce((lambda x, y: x * y), [2, 3, 4])    # 24
 577     
 578 #-- 生成器函数:yield VS return
 579     def gensquare(N):
 580         for i in range(N):
 581             yield i** 2                # 状态挂起 可以恢复到此时的状态
 582     for i in gensquare(5):             # 使用方法
 583         print(i, end = ' ')            # [0, 1, 4, 9, 16]
 584     x = gensquare(2)                   # x是一个生成对象
 585     next(x)                            # 等同于x.__next__() 返回0
 586     next(x)                            # 等同于x.__next__() 返回1
 587     next(x)                            # 等同于x.__next__() 抛出异常StopIteration
 588     
 589 #-- 生成器表达式:小括号进行列表解析
 590     G = (x ** 2 for x in range(3))     # 使用小括号可以创建所需结果的生成器generator object
 591     next(G), next(G), next(G)          # 和上述中的生成器函数的返回值一致
 592     #(1)生成器(生成器函数/生成器表达式)是单个迭代对象
 593     G = (x ** 2 for x in range(4))
 594     I1 = iter(G)                       # 这里实际上iter(G) = G
 595     next(I1)                           # 输出0
 596     next(G)                            # 输出1
 597     next(I1)                           # 输出4
 598     #(2)生成器不保留迭代后的结果
 599     gen = (i for i in range(4))
 600     2 in gen                           # 返回True
 601     3 in gen                           # 返回True
 602     1 in gen                           # 返回False,其实检测2的时候,1已经就不在生成器中了,即1已经被迭代过了,同理2、3也不在了
 603 
 604 #-- 本地变量是静态检测的
 605     X = 22                             # 全局变量X的声明和定义
 606     def test():
 607         print(X)                       # 如果没有下一语句 则该句合法 打印全局变量X
 608         X = 88                         # 这一语句使得上一语句非法 因为它使得X变成了本地变量 上一句变成了打印一个未定义的本地变量(局部变量)
 609         if False:                      # 即使这样的语句 也会把print语句视为非法语句 因为:
 610             X = 88                     # Python会无视if语句而仍然声明了局部变量X
 611     def test():                        # 改进
 612         global X                       # 声明变量X为全局变量
 613         print(X)                       # 打印全局变量X
 614         X = 88                         # 改变全局变量X
 615         
 616 #-- 函数的默认值是在函数定义的时候实例化的 而不是在调用的时候 例子:
 617     def foo(numbers=[]):               # 这里的[]是可变的
 618         numbers.append(9)    
 619         print(numbers)
 620     foo()                              # first time, like before, [9]
 621     foo()                              # second time, not like before, [9, 9]
 622     foo()                              # third time, not like before too, [9, 9, 9]
 623     # 改进:
 624     def foo(numbers=None):
 625         if numbers is None: numbers = []
 626         numbers.append(9)
 627         print(numbers)
 628     # 另外一个例子 参数的默认值为不可变的:
 629     def foo(count=0):                  # 这里的0是数字, 是不可变的
 630         count += 1
 631         print(count)
 632     foo()                              # 输出1
 633     foo()                              # 还是输出1
 634     foo(3)                             # 输出4
 635     foo()                              # 还是输出1
 636     
 637 
 638 """函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子----函数例子"""
 639 
 640     """数学运算类"""
 641     abs(x)                              # 求绝对值,参数可以是整型,也可以是复数,若参数是复数,则返回复数的模
 642     complex([real[, imag]])             # 创建一个复数
 643     divmod(a, b)                        # 分别取商和余数,注意:整型、浮点型都可以
 644     float([x])                          # 将一个字符串或数转换为浮点数。如果无参数将返回0.0
 645     int([x[, base]])                    # 将一个字符串或浮点数转换为int类型,base表示进制
 646     long([x[, base]])                   # 将一个字符串或浮点数转换为long类型
 647     pow(x, y)                           # 返回x的y次幂
 648     range([start], stop[, step])        # 产生一个序列,默认从0开始
 649     round(x[, n])                       # 四舍五入
 650     sum(iterable[, start])              # 对集合求和
 651     oct(x)                              # 将一个数字转化为8进制字符串
 652     hex(x)                              # 将一个数字转换为16进制字符串
 653     chr(i)                              # 返回给定int类型对应的ASCII字符
 654     unichr(i)                           # 返回给定int类型的unicode
 655     ord(c)                              # 返回ASCII字符对应的整数
 656     bin(x)                              # 将整数x转换为二进制字符串
 657     bool([x])                           # 将x转换为Boolean类型
 658     
 659     """集合类操作"""
 660     basestring()                        # str和unicode的超类,不能直接调用,可以用作isinstance判断
 661     format(value [, format_spec])       # 格式化输出字符串,格式化的参数顺序从0开始,如“I am {0},I like {1}”
 662     enumerate(sequence[, start=0])      # 返回一个可枚举的对象,注意它有第二个参数
 663     iter(obj[, sentinel])               # 生成一个对象的迭代器,第二个参数表示分隔符
 664     max(iterable[, args...][key])       # 返回集合中的最大值
 665     min(iterable[, args...][key])       # 返回集合中的最小值
 666     dict([arg])                         # 创建数据字典
 667     list([iterable])                    # 将一个集合类转换为另外一个集合类
 668     set()                               # set对象实例化
 669     frozenset([iterable])               # 产生一个不可变的set
 670     tuple([iterable])                   # 生成一个tuple类型
 671     str([object])                       # 转换为string类型
 672     sorted(iterable[, cmp[, key[, reverse]]])             # 集合排序
 673         L = [('b',2),('a',1),('c',3),('d',4)]
 674         sorted(L, key=lambda x: x[1], reverse=True)       # 使用Key参数和reverse参数
 675         sorted(L, key=lambda x: (x[0], x[1]))             # 使用key参数进行多条件排序,即如果x[0]相同,则比较x[1]
 676 
 677     """逻辑判断"""
 678     all(iterable)                       # 集合中的元素都为真的时候为真,特别的,若为空串返回为True
 679     any(iterable)                       # 集合中的元素有一个为真的时候为真,特别的,若为空串返回为False
 680     cmp(x, y)                           # 如果x < y ,返回负数;x == y, 返回0;x > y,返回正数
 681 
 682     """IO操作"""
 683     file(filename [, mode [, bufsize]]) # file类型的构造函数。
 684     input([prompt])                     # 获取用户输入,推荐使用raw_input,因为该函数将不会捕获用户的错误输入,意思是自行判断类型
 685     # 在 Built-in Functions 里有一句话是这样写的:Consider using the raw_input() function for general input from users.
 686     raw_input([prompt])                 # 设置输入,输入都是作为字符串处理
 687     open(name[, mode[, buffering]])     # 打开文件,与file有什么不同?推荐使用open
 688     
 689     """其他"""
 690     callable(object)                    # 检查对象object是否可调用
 691     classmethod(func)                   # 用来说明这个func是个类方法
 692     staticmethod(func)                  # 用来说明这个func为静态方法
 693     dir([object])                       # 不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
 694     help(obj)                           # 返回obj的帮助信息
 695     eval(expression)                    # 计算表达式expression的值,并返回
 696     exec(str)                           # 将str作为Python语句执行
 697     execfile(filename)                  # 用法类似exec(),不同的是execfile的参数filename为文件名,而exec的参数为字符串。
 698     filter(function, iterable)          # 构造一个序列,等价于[item for item in iterable if function(item)],function返回值为True或False的函数
 699         list(filter(bool, range(-3, 4)))# 返回[-3, -2, -1, 1, 2, 3], 没有0
 700     hasattr(object, name)               # 判断对象object是否包含名为name的特性
 701     getattr(object, name [, defalut])   # 获取一个类的属性
 702     setattr(object, name, value)        # 设置属性值
 703     delattr(object, name)               # 删除object对象名为name的属性
 704     globals()                           # 返回一个描述当前全局符号表的字典
 705     hash(object)                        # 如果对象object为哈希表类型,返回对象object的哈希值
 706     id(object)                          # 返回对象的唯一标识,一串数字
 707     isinstance(object, classinfo)       # 判断object是否是class的实例
 708         isinstance(1, int)              # 判断是不是int类型
 709         isinstance(1, (int, float))     # isinstance的第二个参数接受一个元组类型
 710     issubclass(class, classinfo)        # 判断class是否为classinfo的子类
 711     locals()                            # 返回当前的变量列表
 712     map(function, iterable, ...)        # 遍历每个元素,执行function操作
 713         list(map(abs, range(-3, 4)))    # 返回[3, 2, 1, 0, 1, 2, 3]
 714     next(iterator[, default])           # 类似于iterator.next()
 715     property([fget[, fset[, fdel[, doc]]]])           # 属性访问的包装类,设置后可以通过c.x=value等来访问setter和getter
 716     reduce(function, iterable[, initializer])         # 合并操作,从第一个开始是前两个参数,然后是前两个的结果与第三个合并进行处理,以此类推
 717         def add(x,y):return x + y 
 718         reduce(add, range(1, 11))                     # 返回55 (注:1+2+3+4+5+6+7+8+9+10 = 55)
 719         reduce(add, range(1, 11), 20)                 # 返回75
 720     reload(module)                      # 重新加载模块
 721     repr(object)                        # 将一个对象变幻为可打印的格式
 722     slice(start, stop[, step])          # 产生分片对象
 723     type(object)                        # 返回该object的类型
 724     vars([object])                      # 返回对象的变量名、变量值的字典
 725         a = Class();                    # Class为一个空类
 726         a.name = 'qi', a.age = 9
 727         vars(a)                         # {'name':'qi', 'age':9}
 728     zip([iterable, ...])                # 返回对应数组
 729         list(zip([1, 2, 3], [4, 5, 6])) # [(1, 4), (2, 5), (3, 6)]
 730         a = [1, 2, 3],  b = ["a", "b", "c"]
 731         z = zip(a, b)                   # 压缩:[(1, "a"), (2, "b"), (3, "c")]
 732         zip(*z)                         # 解压缩:[(1, 2, 3), ("a", "b", "c")]
 733     unicode(string, encoding, errors)   # 将字符串string转化为unicode形式,string为encoded string。
 734 
 735     
 736 """模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle----模块Moudle"""
 737 
 738 #-- Python模块搜索路径:
 739     """
 740     (1)程序的主目录    (2)PYTHONPATH目录 (3)标准链接库目录 (4)任何.pth文件的内容
 741     """
 742     
 743 #-- 查看全部的模块搜索路径
 744     import sys
 745     sys.path
 746     sys.argv                            # 获得脚本的参数
 747     sys.builtin_module_names            # 查找内建模块
 748     sys.platform                        # 返回当前平台 出现如: "win32" "linux" "darwin"等
 749     sys.modules                         # 查找已导入的模块
 750     sys.modules.keys()
 751     sys.stdout                          # stdout 和 stderr 都是类文件对象,但是它们都是只写的。它们都没有 read 方法,只有 write 方法
 752     sys.stdout.write("hello")
 753     sys.stderr
 754     sys.stdin   
 755 
 756 #-- 模块的使用代码
 757     import module1, module2             # 导入module1 使用module1.printer()
 758     from module1 import printer         # 导入module1中的printer变量 使用printer()
 759     from module1 import *               # 导入module1中的全部变量 使用不必添加module1前缀
 760 
 761 #-- 重载模块reload: 这是一个内置函数 而不是一条语句
 762     from imp import reload
 763     reload(module)
 764     
 765 #-- 模块的包导入:使用点号(.)而不是路径(dir1\dir2)进行导入
 766     import dir1.dir2.mod                # d导入包(目录)dir1中的包dir2中的mod模块 此时dir1必须在Python可搜索路径中
 767     from dir1.dir2.mod import *         # from语法的包导入
 768 
 769 #-- __init__.py包文件:每个导入的包中都应该包含这么一个文件
 770     """
 771     该文件可以为空
 772     首次进行包导入时 该文件会自动执行
 773     高级功能:在该文件中使用__all__列表来定义包(目录)以from*的形式导入时 需要导入什么
 774     """
 775     
 776 #-- 包相对导入:使用点号(.) 只能使用from语句
 777     from . import spam                  # 导入当前目录下的spam模块(Python2: 当前目录下的模块, 直接导入即可)
 778     from .spam import name              # 导入当前目录下的spam模块的name属性(Python2: 当前目录下的模块, 直接导入即可,不用加.)
 779     from .. import spam                 # 导入当前目录的父目录下的spam模块
 780     
 781 #-- 包相对导入与普通导入的区别
 782     from string import *                # 这里导入的string模块为sys.path路径上的 而不是本目录下的string模块(如果存在也不是)
 783     from .string import *               # 这里导入的string模块为本目录下的(不存在则导入失败) 而不是sys.path路径上的
 784     
 785 #-- 模块数据隐藏:最小化from*的破坏
 786     _X                                  # 变量名前加下划线可以防止from*导入时该变量名被复制出去
 787     __all__ = ['x', 'x1', 'x2']         # 使用__all__列表指定from*时复制出去的变量名(变量名在列表中为字符串形式)
 788 
 789 #-- 可以使用__name__进行模块的单元测试:当模块为顶层执行文件时值为'__main__' 当模块被导入时为模块名
 790     if __name__ == '__main__':
 791         doSomething
 792     # 模块属性中还有其他属性,例如:
 793     __doc__                             # 模块的说明文档
 794     __file__                            # 模块文件的文件名,包括全路径
 795     __name__                            # 主文件或者被导入文件
 796     __package__                         # 模块所在的包
 797         
 798 #-- import语句from语句的as扩展
 799     import modulename as name
 800     from modulename import attrname as name
 801     
 802 #-- 得到模块属性的几种方法 假设为了得到name属性的值
 803     M.name
 804     M.__dict__['name']
 805     sys.modules['M'].name
 806     getattr(M, 'name')
 807     
 808 
 809 """类与面向对象----类与面向对象----类与面向对象----类与面向对象----类与面向对象----类与面向对象----类与面向对象----类与面向对象----类与面向对象----类与面向对象"""
 810 
 811 #-- 最普通的类
 812     class C1(C2, C3):
 813         spam = 42                       # 数据属性
 814         def __init__(self, name):       # 函数属性:构造函数
 815             self.name = name
 816         def __del__(self):              # 函数属性:析构函数
 817             print("goodbey ", self.name)    
 818     I1 = C1('bob')
 819     
 820 #-- Python的类没有基于参数的函数重载
 821     class FirstClass(object):
 822         def test(self, string):
 823             print(string)
 824         def test(self):                 # 此时类中只有一个test函数 即后者test(self) 它覆盖掉前者带参数的test函数
 825             print("hello world")
 826 
 827 #-- 子类扩展超类: 尽量调用超类的方法
 828     class Manager(Person):
 829         def giveRaise(self, percent, bonus = .10):
 830             self.pay = int(self.pay*(1 + percent + bonus))     # 不好的方式 复制粘贴超类代码
 831             Person.giveRaise(self, percent + bonus)            # 好的方式 尽量调用超类方法
 832 
 833 #-- 类内省工具
 834     bob = Person('bob')
 835     bob.__class__                       # <class 'Person'>
 836     bob.__class__.__name__              # 'Person'
 837     bob.__dict__                        # {'pay':0, 'name':'bob', 'job':'Manager'}
 838     
 839 #-- 返回1中 数据属性spam是属于类 而不是对象
 840     I1 = C1('bob'); I2 = C2('tom')      # 此时I1和I2的spam都为42 但是都是返回的C1的spam属性
 841     C1.spam = 24                        # 此时I1和I2的spam都为24
 842     I1.spam = 3                         # 此时I1新增自有属性spam 值为3 I2和C1的spam还都为24
 843     
 844 #-- 类方法调用的两种方式
 845     instance.method(arg...)
 846     class.method(instance, arg...)
 847     
 848 #-- 抽象超类的实现方法
 849     # (1)某个函数中调用未定义的函数 子类中定义该函数
 850         def delegate(self):
 851             self.action()               # 本类中不定义action函数 所以使用delegate函数时就会出错
 852     # (2)定义action函数 但是返回异常
 853         def action(self):
 854             raise NotImplementedError("action must be defined")
 855     # (3)上述的两种方法还都可以定义实例对象 实际上可以利用@装饰器语法生成不能定义的抽象超类
 856         from abc import ABCMeta, abstractmethod
 857         class Super(metaclass = ABCMeta):
 858             @abstractmethod
 859             def action(self): pass
 860         x = Super()                     # 返回 TypeError: Can't instantiate abstract class Super with abstract methods action
 861     
 862 #-- # OOP和继承: "is-a"的关系
 863     class A(B):
 864         pass
 865     a = A()
 866     isinstance(a, B)                    # 返回True, A是B的子类 a也是B的一种
 867     # OOP和组合: "has-a"的关系
 868     pass
 869     # OOP和委托: "包装"对象 在Python中委托通常是以"__getattr__"钩子方法实现的, 这个方法会拦截对不存在属性的读取
 870     # 包装类(或者称为代理类)可以使用__getattr__把任意读取转发给被包装的对象
 871     class wrapper(object):
 872         def __init__(self, object):
 873             self.wrapped = object
 874         def __getattr(self, attrname):
 875             print('Trace: ', attrname)
 876             return getattr(self.wrapped, attrname)
 877     # 注:这里使用getattr(X, N)内置函数以变量名字符串N从包装对象X中取出属性 类似于X.__dict__[N]
 878     x = wrapper([1, 2, 3])
 879     x.append(4)                         # 返回 "Trace: append" [1, 2, 3, 4]
 880     x = wrapper({'a':1, 'b':2})
 881     list(x.keys())                      # 返回 "Trace: keys" ['a', 'b']
 882 
 883 #-- 类的伪私有属性:使用__attr
 884     class C1(object):
 885         def __init__(self, name):
 886             self.__name = name          # 此时类的__name属性为伪私有属性 原理 它会自动变成self._C1__name = name
 887         def __str__(self):
 888             return 'self.name = %s' % self.__name
 889     I = C1('tom')
 890     print(I)                            # 返回 self.name = tom
 891     I.__name = 'jeey'                   # 这里无法访问 __name为伪私有属性
 892     I._C1__name = 'jeey'                # 这里可以修改成功 self.name = jeey
 893     
 894 #-- 类方法是对象:无绑定类方法对象 / 绑定实例方法对象
 895     class Spam(object):
 896         def doit(self, message):
 897             print(message)
 898         def selfless(message)
 899             print(message)
 900     obj = Spam()
 901     x = obj.doit                        # 类的绑定方法对象 实例 + 函数
 902     x('hello world')
 903     x = Spam.doit                       # 类的无绑定方法对象 类名 + 函数
 904     x(obj, 'hello world')
 905     x = Spam.selfless                   # 类的无绑定方法函数 在3.0之前无效
 906     x('hello world')
 907 
 908 #-- 获取对象信息: 属性和方法
 909     a = MyObject()
 910     dir(a)                              # 使用dir函数
 911     hasattr(a, 'x')                     # 测试是否有x属性或方法 即a.x是否已经存在
 912     setattr(a, 'y', 19)                 # 设置属性或方法 等同于a.y = 19
 913     getattr(a, 'z', 0)                  # 获取属性或方法 如果属性不存在 则返回默认值0
 914     #这里有个小技巧,setattr可以设置一个不能访问到的属性,即只能用getattr获取
 915     setattr(a, "can't touch", 100)      # 这里的属性名带有空格,不能直接访问
 916     getattr(a, "can't touch", 0)        # 但是可以用getattr获取
 917 
 918 #-- 为类动态绑定属性或方法: MethodType方法
 919     # 一般创建了一个class的实例后, 可以给该实例绑定任何属性和方法, 这就是动态语言的灵活性
 920     class Student(object):
 921         pass
 922     s = Student()
 923     s.name = 'Michael'                  # 动态给实例绑定一个属性
 924     def set_age(self, age):             # 定义一个函数作为实例方法
 925         self.age = age
 926     from types import MethodType
 927     s.set_age = MethodType(set_age, s)  # 给实例绑定一个方法 类的其他实例不受此影响
 928     s.set_age(25)                       # 调用实例方法
 929     Student.set_age = MethodType(set_age, Student)    # 为类绑定一个方法 类的所有实例都拥有该方法
 930 
 931     
 932 """类的高级话题----类的高级话题----类的高级话题----类的高级话题----类的高级话题----类的高级话题----类的高级话题----类的高级话题----类的高级话题----类的高级话题"""
 933     
 934 #-- 多重继承: "混合类", 搜索方式"从下到上 从左到右 广度优先"
 935     class A(B, C):
 936         pass
 937 
 938 #-- 类的继承和子类的初始化
 939     # 1.子类定义了__init__方法时,若未显示调用基类__init__方法,python不会帮你调用。
 940     # 2.子类未定义__init__方法时,python会自动帮你调用首个基类的__init__方法,注意是首个。
 941     # 3.子类显示调用基类的初始化函数:
 942     class FooParent(object):
 943         def __init__(self, a):
 944             self.parent = 'I\'m the Parent.'
 945             print('Parent:a=' + str(a))
 946         def bar(self, message):
 947             print(message + ' from Parent')
 948     class FooChild(FooParent):
 949         def __init__(self, a):
 950             FooParent.__init__(self, a)
 951             print('Child:a=' + str(a))
 952         def bar(self, message):
 953             FooParent.bar(self, message)
 954             print(message + ' from Child')
 955     fooChild = FooChild(10)
 956     fooChild.bar('HelloWorld')
 957     
 958 #-- #实例方法 / 静态方法 / 类方法
 959     class Methods(object):
 960         def imeth(self, x): print(self, x)      # 实例方法:传入的是实例和数据,操作的是实例的属性
 961         def smeth(x): print(x)                  # 静态方法:只传入数据 不传入实例,操作的是类的属性而不是实例的属性
 962         def cmeth(cls, x): print(cls, x)        # 类方法:传入的是类对象和数据
 963         smeth = staticmethod(smeth)             # 调用内置函数,也可以使用@staticmethod
 964         cmeth = classmethod(cmeth)              # 调用内置函数,也可以使用@classmethod
 965     obj = Methods()
 966     obj.imeth(1)                                # 实例方法调用 <__main__.Methods object...> 1
 967     Methods.imeth(obj, 2)                       # <__main__.Methods object...> 2
 968     Methods.smeth(3)                            # 静态方法调用 3
 969     obj.smeth(4)                                # 这里可以使用实例进行调用
 970     Methods.cmeth(5)                            # 类方法调用 <class '__main__.Methods'> 5
 971     obj.cmeth(6)                                # <class '__main__.Methods'> 6
 972     
 973 #-- 函数装饰器:是它后边的函数的运行时的声明 由@符号以及后边紧跟的"元函数"(metafunction)组成
 974         @staticmethod
 975         def smeth(x): print(x)
 976     # 等同于:
 977         def smeth(x): print(x)
 978         smeth = staticmethod(smeth)
 979     # 同理
 980         @classmethod
 981         def cmeth(cls, x): print(x)
 982     # 等同于
 983         def cmeth(cls, x): print(x)
 984         cmeth = classmethod(cmeth)
 985     
 986 #-- 类修饰器:是它后边的类的运行时的声明 由@符号以及后边紧跟的"元函数"(metafunction)组成
 987         def decorator(aClass):.....
 988         @decorator
 989         class C(object):....
 990     # 等同于:
 991         class C(object):....
 992         C = decorator(C)
 993 
 994 #-- 限制class属性: __slots__属性
 995     class Student(object):
 996         __slots__ = ('name', 'age')             # 限制Student及其实例只能拥有name和age属性
 997     # __slots__属性只对当前类起作用, 对其子类不起作用
 998     # __slots__属性能够节省内存
 999     # __slots__属性可以为列表list,或者元组tuple
1000     
1001 #-- 类属性高级话题: @property
1002     # 假设定义了一个类:C,该类必须继承自object类,有一私有变量_x
1003     class C(object):
1004         def __init__(self):
1005             self.__x = None
1006     # 第一种使用属性的方法
1007         def getx(self):
1008             return self.__x
1009         def setx(self, value):
1010             self.__x = value
1011         def delx(self):
1012             del self.__x
1013         x = property(getx, setx, delx, '')
1014     # property函数原型为property(fget=None,fset=None,fdel=None,doc=None)
1015     # 使用
1016     c = C()
1017     c.x = 100                         # 自动调用setx方法
1018     y = c.x                           # 自动调用getx方法
1019     del c.x                           # 自动调用delx方法
1020     # 第二种方法使用属性的方法
1021         @property
1022         def x(self):
1023             return self.__x
1024         @x.setter
1025         def x(self, value):
1026            self.__x = value
1027         @x.deleter
1028         def x(self):
1029            del self.__x
1030     # 使用
1031     c = C()
1032     c.x = 100                         # 自动调用setter方法
1033     y = c.x                           # 自动调用x方法
1034     del c.x                           # 自动调用deleter方法
1035     
1036 #-- 定制类: 重写类的方法
1037     # (1)__str__方法、__repr__方法: 定制类的输出字符串
1038     # (2)__iter__方法、next方法: 定制类的可迭代性
1039     class Fib(object):
1040         def __init__(self):
1041             self.a, self.b = 0, 1     # 初始化两个计数器a,b
1042         def __iter__(self):
1043             return self               # 实例本身就是迭代对象,故返回自己
1044         def next(self):
1045             self.a, self.b = self.b, self.a + self.b
1046             if self.a > 100000:       # 退出循环的条件
1047                 raise StopIteration()
1048             return self.a             # 返回下一个值
1049     for n in Fib():
1050         print(n)                      # 使用
1051     # (3)__getitem__方法、__setitem__方法: 定制类的下标操作[] 或者切片操作slice
1052     class Indexer(object):
1053         def __init__(self):
1054             self.data = {}
1055         def __getitem__(self, n):             # 定义getitem方法
1056             print('getitem:', n)                
1057             return self.data[n]
1058         def __setitem__(self, key, value):    # 定义setitem方法
1059             print('setitem:key = {0}, value = {1}'.format(key, value))
1060             self.data[key] = value
1061     test = Indexer()
1062     test[0] = 1;   test[3] = '3'              # 调用setitem方法
1063     print(test[0])                            # 调用getitem方法
1064     # (4)__getattr__方法: 定制类的属性操作
1065     class Student(object):
1066         def __getattr__(self, attr):          # 定义当获取类的属性时的返回值
1067             if attr=='age':
1068                 return 25                     # 当获取age属性时返回25
1069         raise AttributeError('object has no attribute: %s' % attr)
1070         # 注意: 只有当属性不存在时 才会调用该方法 且该方法默认返回None 需要在函数最后引发异常
1071     s = Student()
1072     s.age                                     # s中age属性不存在 故调用__getattr__方法 返回25
1073     # (5)__call__方法: 定制类的'可调用'性
1074     class Student(object):
1075         def __call__(self):                   # 也可以带参数
1076             print('Calling......')
1077     s = Student()
1078     s()                                       # s变成了可调用的 也可以带参数
1079     callable(s)                               # 测试s的可调用性 返回True
1080     #    (6)__len__方法:求类的长度
1081     def __len__(self):
1082         return len(self.data)
1083     
1084 #-- 动态创建类type()
1085     # 一般创建类 需要在代码中提前定义
1086         class Hello(object):
1087             def hello(self, name='world'):
1088                 print('Hello, %s.' % name)
1089         h = Hello()
1090         h.hello()                             # Hello, world
1091         type(Hello)                           # Hello是一个type类型 返回<class 'type'>
1092         type(h)                               # h是一个Hello类型 返回<class 'Hello'>
1093     # 动态类型语言中 类可以动态创建 type函数可用于创建新类型
1094         def fn(self, name='world'):           # 先定义函数
1095             print('Hello, %s.' % name)
1096         Hello = type('Hello', (object,), dict(hello=fn))    # 创建Hello类 type原型: type(name, bases, dict)
1097         h = Hello()                           # 此时的h和上边的h一致
1098 
1099 
1100 """异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关----异常相关"""
1101     
1102 #-- #捕获异常: 
1103         try:
1104         except:                               # 捕获所有的异常 等同于except Exception:
1105         except name:                          # 捕获指定的异常
1106         except name, value:                   # 捕获指定的异常和额外的数据(实例)
1107         except (name1, name2):
1108         except (name1, name2), value:
1109         except name4 as X:
1110         else:                                 # 如果没有发生异常
1111         finally:                              # 总会执行的部分
1112     # 引发异常: raise子句(raise IndexError)
1113         raise <instance>                      # raise instance of a class, raise IndexError()
1114         raise <class>                         # make and raise instance of a class, raise IndexError
1115         raise                                 # reraise the most recent exception
1116 
1117 #-- Python3.x中的异常链: raise exception from otherException
1118     except Exception as X:
1119         raise IndexError('Bad') from X
1120         
1121 #-- assert子句: assert <test>, <data>
1122     assert x < 0, 'x must be negative'
1123     
1124 #-- with/as环境管理器:作为常见的try/finally用法模式的替代方案
1125     with expression [as variable], expression [as variable]:
1126     # 例子:
1127         with open('test.txt') as myfile:
1128             for line in myfile: print(line)
1129     # 等同于:
1130         myfile = open('test.txt')
1131         try:
1132             for line in myfile: print(line)
1133         finally:
1134             myfile.close()
1135 
1136 #-- 用户自定义异常: class Bad(Exception):.....
1137     """
1138     Exception超类 / except基类即可捕获到其所有子类
1139     Exception超类有默认的打印消息和状态 当然也可以定制打印显示:
1140     """
1141     class MyBad(Exception):
1142         def __str__(self):
1143             return '定制的打印消息'
1144     try:
1145         MyBad()
1146     except MyBad as x:
1147         print(x)
1148     
1149 #-- 用户定制异常数据
1150     class FormatError(Exception):
1151         def __init__(self, line ,file):
1152             self.line = line
1153             self.file = file
1154     try:
1155         raise FormatError(42, 'test.py')
1156     except FormatError as X:
1157         print('Error at ', X.file, X.line)
1158     # 用户定制异常行为(方法):以记录日志为例
1159     class FormatError(Exception):
1160         logfile = 'formaterror.txt'
1161         def __init__(self, line ,file):
1162             self.line = line
1163             self.file = file
1164         def logger(self):
1165             open(self.logfile, 'a').write('Error at ', self.file, self.line)
1166     try:
1167         raise FormatError(42, 'test.py')
1168     except FormatError as X:
1169         X.logger()
1170 
1171 #-- 关于sys.exc_info:允许一个异常处理器获取对最近引发的异常的访问
1172     try:
1173         ......
1174     except:
1175         # 此时sys.exc_info()返回一个元组(type, value, traceback)
1176         # type:正在处理的异常的异常类型
1177         # value:引发的异常的实例
1178         # traceback:堆栈信息
1179         
1180 #-- 异常层次
1181     BaseException
1182     +-- SystemExit
1183     +-- KeyboardInterrupt
1184     +-- GeneratorExit
1185     +-- Exception
1186         +-- StopIteration
1187         +-- ArithmeticError
1188         +-- AssertionError
1189         +-- AttributeError
1190         +-- BufferError
1191         +-- EOFError
1192         +-- ImportError
1193         +-- LookupError
1194         +-- MemoryError
1195         +-- NameError
1196         +-- OSError
1197         +-- ReferenceError
1198         +-- RuntimeError
1199         +-- SyntaxError
1200         +-- SystemError
1201         +-- TypeError
1202         +-- ValueError
1203         +-- Warning
1204 
1205     
1206 """Unicode和字节字符串---Unicode和字节字符串----Unicode和字节字符串----Unicode和字节字符串----Unicode和字节字符串----Unicode和字节字符串----Unicode和字节字符串"""
1207 
1208 #-- Python的字符串类型
1209     """Python2.x"""
1210     # 1.str表示8位文本和二进制数据
1211     # 2.unicode表示宽字符Unicode文本
1212     """Python3.x"""
1213     # 1.str表示Unicode文本(8位或者更宽)
1214     # 2.bytes表示不可变的二进制数据
1215     # 3.bytearray是一种可变的bytes类型
1216 
1217 #-- 字符编码方法
1218     """ASCII"""                   # 一个字节,只包含英文字符,0到127,共128个字符,利用函数可以进行字符和数字的相互转换
1219     ord('a')                      # 字符a的ASCII码为97,所以这里返回97
1220     chr(97)                       # 和上边的过程相反,返回字符'a'
1221     """Latin-1"""                 # 一个字节,包含特殊字符,0到255,共256个字符,相当于对ASCII码的扩展
1222     chr(196)                      # 返回一个特殊字符:Ä
1223     """Unicode"""                 # 宽字符,一个字符包含多个字节,一般用于亚洲的字符集,比如中文有好几万字
1224     """UTF-8"""                   # 可变字节数,小于128的字符表示为单个字节,128到0X7FF之间的代码转换为两个字节,0X7FF以上的代码转换为3或4个字节
1225     # 注意:可以看出来,ASCII码是Latin-1和UTF-8的一个子集
1226     # 注意:utf-8是unicode的一种实现方式,unicode、gbk、gb2312是编码字符集
1227     
1228 #-- 查看Python中的字符串编码名称,查看系统的编码
1229     import encodings
1230     help(encoding)
1231     import sys
1232     sys.platform                  # 'win64'
1233     sys.getdefaultencoding()      # 'utf-8'
1234     sys.getdefaultencoding()      # 返回当前系统平台的编码类型
1235     sys.getsizeof(object)         # 返回object占有的bytes的大小
1236     
1237 #-- 源文件字符集编码声明: 添加注释来指定想要的编码形式 从而改变默认值 注释必须出现在脚本的第一行或者第二行
1238     """说明:其实这里只会检查#和coding:utf-8,其余的字符都是为了美观加上的"""
1239     # _*_ coding: utf-8 _*_
1240     # coding = utf-8
1241     
1242 #-- #编码: 字符串 --> 原始字节       #解码: 原始字节 --> 字符串
1243 
1244 #-- Python3.x中的字符串应用
1245     s = '...'                     # 构建一个str对象,不可变对象
1246     b = b'...'                    # 构建一个bytes对象,不可变对象
1247     s[0], b[0]                    # 返回('.', 113)
1248     s[1:], b[1:]                  # 返回('..', b'..')
1249     B = B"""
1250         xxxx
1251         yyyy
1252         """
1253     # B = b'\nxxxx\nyyyy\n'
1254     # 编码,将str字符串转化为其raw bytes形式:
1255         str.encode(encoding = 'utf-8', errors = 'strict')
1256         bytes(str, encoding)
1257     # 编码例子:
1258         S = 'egg'
1259         S.encode()                    # b'egg'
1260         bytes(S, encoding = 'ascii')  # b'egg'
1261     # 解码,将raw bytes字符串转化为str形式:
1262         bytes.decode(encoding = 'utf-8', errors = 'strict')
1263         str(bytes_or_buffer[, encoding[, errors]])
1264     # 解码例子:
1265         B = b'spam'
1266         B.decode()                # 'spam'
1267         str(B)                    # "b'spam'",不带编码的str调用,结果为打印该bytes对象
1268         str(B, encoding = 'ascii')# 'spam',带编码的str调用,结果为转化该bytes对象
1269     
1270 #-- Python2.x的编码问题
1271     u = u''
1272     print repr(u)                 # u'\xba\xba'
1273     s = u.encode('UTF-8')
1274     print repr(s)                 # '\xc2\xba\xc2\xba'
1275     u2 = s.decode('UTF-8')
1276     print repr(u2)                # u'\xba\xba'
1277     # 对unicode进行解码是错误的
1278     s2 = u.decode('UTF-8')        # UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
1279     # 同样,对str进行编码也是错误的
1280     u2 = s.encode('UTF-8')        # UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)
1281 
1282 #-- bytes对象
1283     B = b'abc'
1284     B = bytes('abc', 'ascii')
1285     B = bytes([97, 98, 99])
1286     B = 'abc'.encode()
1287     # bytes对象的方法调用基本和str类型一致 但:B[0]返回的是ASCII码值97, 而不是b'a'
1288     
1289 #-- #文本文件: 根据Unicode编码来解释文件内容,要么是平台的默认编码,要么是指定的编码类型
1290     # 二进制文件:表示字节值的整数的一个序列 open('bin.txt', 'rb')
1291     
1292 #-- Unicode文件
1293     s = 'A\xc4B\xe8C'             # s = 'A?BèC'  len(s) = 5
1294     #手动编码
1295         l = s.encode('latin-1')   # l = b'A\xc4B\xe8C'  len(l) = 5
1296         u = s.encode('utf-8')     # u = b'A\xc3\x84B\xc3\xa8C'  len(u) = 7
1297     #文件输出编码
1298         open('latindata', 'w', encoding = 'latin-1').write(s)
1299         l = open('latindata', 'rb').read()                        # l = b'A\xc4B\xe8C'  len(l) = 5
1300         open('uft8data', 'w', encoding = 'utf-8').write(s)
1301         u = open('uft8data', 'rb').read()                         # u = b'A\xc3\x84B\xc3\xa8C'  len(u) = 7
1302     #文件输入编码
1303         s = open('latindata', 'r', encoding = 'latin-1').read()   # s = 'A?BèC'  len(s) = 5
1304         s = open('latindata', 'rb').read().decode('latin-1')      # s = 'A?BèC'  len(s) = 5
1305         s = open('utf8data', 'r', encoding = 'utf-8').read()      # s = 'A?BèC'  len(s) = 5
1306         s = open('utf8data', 'rb').read().decode('utf-8')         # s = 'A?BèC'  len(s) = 5
1307         
1308 
1309 """其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他----其他"""
1310 
1311 #-- Python实现任意深度的赋值 例如a[0] = 'value1'; a[1][2] = 'value2'; a[3][4][5] = 'value3'
1312 
1313     class MyDict(dict):
1314         def __setitem__(self, key, value):                 # 该函数不做任何改动 这里只是为了输出
1315             print('setitem:', key, value, self)
1316             super().__setitem__(key, value)
1317         def __getitem__(self, item):                       # 主要技巧在该函数
1318             print('getitem:', item, self)                  # 输出信息
1319             # 基本思路: a[1][2]赋值时 需要先取出a[1] 然后给a[1]的[2]赋值
1320             if item not in self:                           # 如果a[1]不存在 则需要新建一个dict 并使得a[1] = dict
1321                 temp = MyDict()                            # 新建的dict: temp
1322                 super().__setitem__(item, temp)            # 赋值a[1] = temp
1323                 return temp                                # 返回temp 使得temp[2] = value有效
1324             return super().__getitem__(item)               # 如果a[1]存在 则直接返回a[1]
1325     # 例子:
1326         test = MyDict()
1327         test[0] = 'test'
1328         print(test[0])
1329         test[1][2] = 'test1'
1330         print(test[1][2])
1331         test[1][3] = 'test2'
1332         print(test[1][3])
1333 
1334 
1335 #-- Python中的多维数组
1336 
1337 
1338     lists = [0] * 3                                        # 扩展list,结果为[0, 0, 0]
1339     lists = [[]] * 3                                       # 多维数组,结果为[[], [], []],但有问题,往下看
1340     lists[0].append(3)                                     # 期望看到的结果[[3], [], []],实际结果[[3], [3], [3]],原因:list*n操作,是浅拷贝,如何避免?往下看
1341     lists = [[] for i in range(3)]                         # 多维数组,结果为[[], [], []]
1342     lists[0].append(3)                                     # 结果为[[3], [], []]
1343     lists[1].append(6)                                     # 结果为[[3], [6], []]
1344     lists[2].append(9)                                     # 结果为[[3], [6], [9]]
1345     lists = [[[] for j in range(4)] for i in range(3)]     # 3行4列,且每一个元素为[]

 

转载于:https://www.cnblogs.com/51try-again/p/10152538.html

g you need to know Python is a high-level, interpreted programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and machine learning. It is known for its simplicity, elegance, readability, and flexibility. Here are some of the key features of Python: 1. Easy to learn: Python has a simple syntax that is easy to understand, making it an excellent language for beginners. 2. Interpreted: Python code is executed line by line by an interpreter, which means that you do not need to compile your code before running it. 3. Object-oriented: Python is an object-oriented language, which means that it is based on the concept of objects. Everything in Python is an object, including integers, strings, and functions. 4. Dynamic typing: Python is dynamically typed, which means that you do not need to specify the data type of a variable when you declare it. 5. Cross-platform: Python runs on multiple platforms, including Windows, Linux, and Mac OS. 6. Large standard library: Python comes with a large standard library that includes modules for tasks such as file I/O, networking, and web development. 7. Third-party libraries: Python has a vast ecosystem of third-party libraries that make it easy to extend the functionality of the language. Some popular libraries include NumPy, Pandas, Matplotlib, and TensorFlow. 8. Open-source: Python is open-source, which means that its source code is freely available and can be modified and distributed by anyone. In summary, Python is a versatile and popular programming language that is widely used for a variety of tasks. Its simplicity, flexibility, and large ecosystem of libraries make it an excellent choice for beginners and experienced programmers alike.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值