Python内置函数_反射类

来源:互联网 发布:黑门市场 知乎 编辑:程序博客网 时间:2024/05/16 13:44

bytearray

bytearray([source [, encoding [, errors]]])返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。可以通过“字节与字节数组操作”章节来查看相关字节数组的内容。下面说明一下几种特别的使用方法:1. 如果source是一个字符串,那么必须给出endcoding是什么样编码的,以便转换为合适的字节保存。2. 如果source是一个整数,那么这个数组将初始化为空字节。3. 如果source是一个有缓冲区接口的对象,那么只读的接口初始到数组里。4. 如果source是一个迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里。如果没有输入任何参数,默认就是初始化数组为0个元素。

callable

callable(object)中文说明:检查对象object是否可调用。如果返回Trueobject仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。注意:类是可调用的,而类的实例实现了__call__()方法才可调用。版本:该函数在python2.x版本中都可用。但是在python3.0版本中被移除,而在python3.2以后版本中被重新添加。
>>> callable(0)False>>> callable("mystring")False>>> def add(a, b):return a + b…>>> callable(add)True>>> class A:def method(self):return 0>>> callable(A)True>>> a = A()>>> callable(a)False>>> class B:def __call__(self):return 0>>> callable(B)True>>> b = B()>>> callable(b)True

classmethod & staticmethod

classmethod:类方法staticmethod:静态方法类方法和静态方法皆可以访问类的静态变量(类变量),但不能访问实例变量在Python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:   1.staticmethod可以不接收参数,classmethod的第一个参数必须是cls      类方法有类变量cls传入,从而可以用cls做一些相关的处理。      并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。   2.静态方法则没有,它基本上跟一个全局函数相同,一般来说用的很少   3.普通方法必须通过类对象的实例进行调用
>>> class a():      @staticmethod      def staticm():         print 'static'      def normalm(self):         print 'nomarl',self      @classmethod      def classm(cls):         print 'class',cls>>> a1=a()>>> a1.normalm()nomarl <__main__.a instance at 0x84dddec>>>> a1.staticm()static>>> a1.classm()class __main__.a>>> type(a)<type 'classobj'>>>> type(a1)<type 'instance'>
>>> class A(object):   @classmethod   def cm(cls):      print '类方法cm(cls)调用者:', cls.__name__   @staticmethod   def sm():      print '静态方法sm()被调用'>>> class B(A):   pass>>> A.cm()类方法cm(cls)调用者: A>>> B.cm()类方法cm(cls)调用者: B>>> A.sm()静态方法sm()被调用>>> B.sm()静态方法sm()被调用

compile

compile(source, filename, mode[, flags[, dont_inherit,[optimize]]])1.这个函数用来编译一段字符串的源码,结果可以生成字节码或者AST(抽像语法树),字节码可以使用函数exec()来执行,而AST可以使用eval()来继续编译。2.参数source是一串字符串的源码,或者是AST对象数组。3.参数filename是读取字符串的文件对象,如果不是从文件里读取源码来编译,那么这里可以放一些用来标识这些代码的字符串。4.参数mode是用来指明那种表示的源码类型;   如果是exec类型,表示这是一个序列语句,可以进行运行;   如果是eval类型,表示这是一个单一的表达式语句,可以用来计算相应的值出来;   如果是single类型,表示这是一个单一语句,采用交互模式执行,   在这种情况下,如果是一个表达式,一般会输出结果,而不是打印为None输出。5.可选参数flags和dont_inherit是用来控制编译源码时的标志,可以查看PEP236文档来了解这些参数,以及相关编译的说明。如果两者使用缺省参数(也即两者都是零值),在调用本函数编译时,主要使用代码中指明的编译特征来对待;如果flags参数设置有值,而dont_inherit没有设置(即是零值),那么编译代码时,不仅源码的编译特征起作用,而且flags指明的特征也起作用,相当两者的并集;如果参数dont_inherit设置有值(即是非零值),编译语句时只有参数flags指明的编译特征值起作用,即是不使用源码里指明的特征。编译特征是按位图的方式设置到参数里,可以查看__future__。6.可选参数optimize是用来指明编译器使用优化的等级;缺省值是-1,表示使用命令行参数-O中获取的优化等级为准;如果设置值为0(即是不用优化,__debug__是设置true),是没有优化;如果设置值为1,assert语句被删除,__debug__设置为false;如果设置值为2,除了设置值为1的功能之外,还会把代码里文档说明也删除掉,达到最佳优化结果。7.本函数编译代码时,如果语法出错会返回SyntaxError;如果代码包含一些空字节,则返回类型错误TypeError。注意事项:1.当采用single或eval类型编译时,如果有多行代码,每行代码后面至少有一个换行符\,否则在code模块编译时就会提示编译的源码不完整错误。在Python 3.2版本之后,允许输入Windows或Mac的换行符;2.当采用exec模式时,不需要在每个行后面输入换行符;在这个版本之后增加了优化参数。
In [16]: str = "for i in range(10): print(i)"In [17]: c = compile(str,'','exec') #编译为字节代码对象In [18]: exec(c)0123456789In [19]: str = "3*x + 4*y"In [20]: c = compile(str,'','eval') #编译为表达式In [23]: x,y = 3,4In [24]: eval(c)Out[24]: 25

dir

dir([object])本函数是用来显示当前作用域里的属性列表,或者参数对象object的属性列表。当没有参数对象时,显示当前作用域所在的属性列表;如果有参数对象,就会显示这个对象拥有的属性列表。本函数在显示对象的属性列表时,查看对象是否存在__dir__()函数,1.如果存在,就调用这个函数,并显示这个函数返回的属性列表。当然用户也可以使用__getattr__()或__getattribute__()函数来定制属性的显示。2.如果对象没有定义__dir__()函数,尝试从对象的__dict__属性来获取属性列表,这样来可能显示属性就不是那么准确了,可能有些属性没有显示,特别使用__getattr__()函数来获取属性的方式。本函数设计的机制是这样的:对不同的类型对象,显示不同属性列表,但主要的原则是显示最重要的属性,而不是全部信息显示方面作为重点。1)如果对象是一个模块对象,属性列表显示主要是对象的名称属性列表。2)如果对象是一个类型或类对象,主要显示是属性名称,并且递归地显示基类的属性名称。3)如果对象是其它类型,主要显示属性名称,类属性名称,递归到基类属性名称。

使用dir()列出当前作用域下,基类,子类,子类对象,子类对象的函数的属性

In [26]:  class A:   ....:     def a(self):   ....:        pass   ....:In [27]: class AI(A):   ....:     def ai(self):   ....:         pass
In [15]: if __name__ == '__main__':   ....:     print 'dir without arguments:',dir()   ....:     print   ....:     print 'dir class A:',dir(A)   ....:     print   ....:     print 'dir class AI:',dir(AI)   ....:     a = AI()   ....:     print   ....:     print 'dir object a(AI):',dir(a)   ....:     print   ....:     print 'dir function a.a',dir(a.a)   ....:dir without arguments: ['A', 'AI', 'In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '_dh', '_i', '_i1', '_i10', '_i11',  '_i12', '_i13', '_i14', '_i15', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7',  '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', '_sh', 'a', 'exit', 'get_ipython', 'quit']dir class A: ['__doc__', '__module__', 'a']dir class AI: ['__doc__', '__module__', 'a', 'ai']dir object a(AI): ['__doc__', '__module__', 'a', 'ai']dir function a.a ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__','__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']

使用dir查找module下的所有类

In [16]: import numpyIn [17]: if __name__ == '__main__':   ....:     print 'dir module numpy',dir(numpy)   ....:dir module numpy ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MachAr','ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO',  'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW',  'ScalarType', 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT',  'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WRAP', '__NUMPY_SETUP__',  '__all__', '__builtins__', '__config__', '__doc__', '__file__', '__git__']

如何找到当前模块下的类
方法一:在module下面直接调用

In [1]: class A:   ...:     def a(self):   ...:         pass   ...:In [2]: class AI(A):   ...:     def ai(self):   ...:         pass   ...:In [3]: curModuleDir = dir() #get dir of current file(module)
In [5]: if __name__ == '__main__':   ...:     print 'dir without arguments:',dir()   ...:     print   ...:     print 'dir class A:',dir(A)   ...:     print   ...:     print 'dir class AI:',dir(AI)   ...:     print   ...:     a = AI()   ...:     print 'dir object a(AI):',dir(a)   ...:     print   ...:     print 'dir function a.a:',dir(a.a)   ...:     print   ...:     print 'dir current file:',curModuleDir   ...:dir without arguments: ['A', 'AI', 'In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_ih', '_ii', '_iii', '_oh', '_sh', 'curModuleDir', 'exit', 'get_ipython', 'quit']dir class A: ['__doc__', '__module__', 'a']dir class AI: ['__doc__', '__module__', 'a', 'ai']dir object a(AI): ['__doc__', '__module__', 'a', 'ai']dir function a.a: ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']dir current file: ['A', 'AI', 'In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '_dh', '_i', '_i1', '_i2', '_i3', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'get_ipython', 'quit']

方法二:import当前module

#A.pyclass A(object):    def a():        passclass AI(object):    """docstring for AI"""    def ai():        pass
In [1]: import A as thisIn [2]: if __name__ == '__main__':   ...:     print 'dir current file:',dir(this)   ...:dir current file: ['A', 'AI', '__builtins__', '__doc__', '__file__', '__name__', '__package__']

方法三:根据module名称查找module,然后调用dir
我们知道module下面有个属性name显示module名称,
怎么能够根据module名称来查找module对象呢?可以借助sys.modules。

In [1]: import sysIn [2]: if __name__ == '__main__':   ...:     print 'dir current file:',dir(sys.modules[__name__])   ...:dir current file: ['In', 'Out', '_', '__', '___','__builtin__','__builtins__','__doc__', '__name__', '__package__','_dh', '_i', '_i1', '_i2', '_ih', '_ii','_iii', '_oh','_sh', 'exit','get_ipython','quit', 'sys']
In [4]: import sysIn [5]: class A:   ...:     def a(self):   ...:         pass   ...:In [6]: class AI(A):   ...:     def ai(self):   ...:         pass   ...:In [7]: if __name__ == '__main__':   ...:     print 'dir current file:',dir(sys.modules[__name__])   ...:dir current file: ['A', 'AI', 'In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '__package__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_ih', '_ii', '_iii', '_oh', '_sh', 'exit', 'get_ipython', 'quit', 'sys']

eval

eval(expression [, globals [, locals]])本函数是用来动态地执行一个表达式的字符串,或者compile函数编译出来的代码对象。参数expression是一个表达式字符串,或者表示编译出来代码对象的名称;参数globals是全局命名空间,可以指定执行表达式时的全局作用域的范围,比如指定某些模块可以使用。如果本参数缺省,就使用当前调用这个函数的当前全局命名空间;参数locals是局部作用域命名空间,是用来指定执行表达式时访问的局部命名空间。如果全局命名空间参数出现,但缺省内置模块,那么会自动拷贝这个模块到全局命名空间,意味着无论怎么设置,都可以使用内置模块。如果两个命名空间,都使用缺省方式,就会使用调用这个函数时的命名空间来查找相应的变量。
为什么要使用这个函数呢?这个函数的原因,应该就是动态语言与编译语言的差别之处,因为在编译语言里要动态地产生代码,基本上是不可能的,但动态语言是可以,意味着软件已经部署到服务器上了,但只要作很少的更改,只好直接修改这部分的代码,就可立即实现变化,不用整个软件重新加载。另外一个,这个功能可以用来机器学习里,比如根据用户使用这个软件频率,以及方式,可动态地修改代码,适应用户的变化。想到这里,是不是具有生命力的能力,可以自我更新代码,实现改良式进步,如果做破坏性的动作,其实就是一个病毒。
>>> eval('1+1')2#全局命名空间为空,使用局部命名空间>>> def make_fn(code):   import math   ALLOWED_LOCALS = {v:getattr(math,v)           for v in filter(              lambda x: x.startswith('_'),dir(math))           }   return eval('lambda x: %s'%code ,None,ALLOWED_LOCALS)>>> f = make_fn('x+1')>>> print f(2)3#使用全局命名空间>>> def make_fng(code):   import math   ALLOWED = {v:getattr(math, v)         for v in filter(lambda x: not x.startswith('_'), dir(math))   }   ALLOWED['__builtins__'] = None   return eval('lambda x: %s' % code, ALLOWED, {})>>> f = make_fng('cos(x)')>>> print f(9)-0.911130261885>>> f = make_fng('cos(x*x)')>>> print f(9)0.776685982022

exec

exec(object[, globals[, locals]])本函数是执行一段语句或函数。参数object是一个字符串的语句或者一个编译过的语句的对象名称。参数globals是全局命名空间,用来指定执行语句时可以访问的全局命名空间;参数locals是局部命名空间,用来指定执行语句时可以访问的局部作用域的命名空间。要注意本函数不会返回任何值,不管函数或语句有任何的返回值语句,比returnyield语句。如果参数globals和locals忽略,就会使用调用时所处的命名空间。这两个参数都要求是字典形式来说明命名空间。
在前面已经学习compile、eval等函数,那么它们之间有什么区别呢?可以简单地认为它们的区别如下:compile函数是只编译字符串代码,而不作任何的执行,但它可以编译表达式或语句。eval函数是**只执行表达式字符串代码,而不执行语句代码。**x = eval('%d + 6' % x)exec函数是**只执行语句代码,而不执行表达式代码**,因为它没有任何返回值。exec('if True: print(6)')
>>> exec('if True: print 100')100
>>> exec('''x = 200if x>100:    print x+200''')400

execfile

execfile(filename [, globals [, locals]])用法类似exec(),不同的是execfile的参数filename为文件名,而exec的参数为字符串。
#A.pyfor b in birds:    print b
In [1]: globals = {   ...: 'birds':['Parrot','Swallow','Albatross']   ...: }In [2]: locals = {}In [3]: execfile('A.py',globals,locals)ParrotSwallowAlbatross

filter

filter(function, iterable)本函数用来从一个迭代对象iterable遍历所有元素,当每个元素作为参数给函数function对象运行之后,判断为True的元素保留下来,而为False的元素则跳过,即是达到过滤不需要元素的目标。参数iterable是可迭代的对象,比如列表、字典、字符串,或者带迭代器的函数对象。参数function是一个能输入元素进判断并返回值的函数,如果这个参数为空,默认使用标识函数identity为缺省函数。当function非空时,相当于生成表达式:item for item in iterable if function(item)) 当function为空时,相当于生成表达式:item for item in iterable if item
>>> l = list(filter(None,[0,1,2,3]))>>> l[1, 2, 3]    #因为0为False>>> l = list(filter(lambda x: x>5,range(10)))>>> l[6, 7, 8, 9]

hash

hash(object)本函数返回对象的哈希值。返回的哈希值是使用一个整数表示,通常使用在字典里,以便实现快速查询键值。参数object输入是**数字类型**时,是根据数值来计算的,比如11.0计算出来是一样的哈希值,因此说这个函数是不区分不同的数值类型。
>>> print hash('abc')-1600925533>>> print hash('ABC')826005955>>> print hash(2.0)2>>> print hash(2)2

isinstance

isinstance(object, classinfo)本函数用来判断对象实例object是否是类classinfo的实例,如果是就返回True,否则返回False。参数classinfo可以是类型,也可以是tuple/dict/list等类型。
>>> class fooA:   pass>>> class fooB:   pass>>> class fooC(fooA):   pass>>> a = fooA()>>> b = fooB()>>> c = fooC()>>> print isinstance(a,fooA)True>>> print isinstance(a,fooB)False>>> print isinstance(b,fooB)True>>> print isinstance(b,fooA)False>>> print isinstance(c,fooA)True>>> print isinstance([],list)True>>> print isinstance((1,),tuple)True>>> print isinstance(dict(one=1),dict)True

issubclass

issubclass(class, classinfo)判断是否是子类  
>>> class fooA:   pass>>> class fooC(fooA):   pass>>> print issubclass(fooC,fooA)True

hasattr

setattr

getattr

delattr

hasattr(object,name):用于判断一个对象里中是否存在name这一特性.
setattr(object, name, value):该函数给对象中的属性赋值,该属性若不存在,则会在对象里创建新的属性
getattr(object, name[, default]),object为对象名,naem为对象属性(必须是字符串),default为name属性不存在时指定的返回内容(可以是字符串,也可以是部分指令),若对象中存在该属性,则函数返回object.name,否则返回default中的内容,若省略default,则返回 AttributeError.
delattr(object, name):删除指定对象的属性,可以配合hasattr使用
In [4]: class test(object):   ...:     name = "john"   ...:     def greet(self):   ...:         print "hello,my name is %s"% name   ...:In [5]: a = test()In [6]: hasattr(a,'name')Out[6]: TrueIn [7]: hasattr(a,'greet')Out[7]: TrueIn [8]: setattr(a,'name','mark')In [9]: print a.namemarkIn [10]: getattr(a,'name','no exit')Out[10]: 'mark'In [11]: getattr(a,'greet','no exit')Out[11]: <bound method test.greet of <__main__.test object at 0x0000000003AB8470>>In [12]: getattr(a,'age','no exit')Out[12]: 'no exit'In [13]: setattr(a,'name','jane')In [14]: a.nameOut[14]: 'jane'In [15]: setattr(a,'age',20)In [16]: a.ageOut[16]: 20In [17]: getattr(a,'nationality',setattr(a,'nationality','Englend'))Out[17]: 'Englend'In [18]: a.nationalityOut[18]: 'Englend'In [19]: if hasattr(a,'age'):   ....:     delattr(a,'age')   ....:In [20]: a.age---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)<ipython-input-20-d50340e1fbb7> in <module>()----> 1 a.ageAttributeError: 'test' object has no attribute 'age'In [21]: b = test()In [22]: b.nationality---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)<ipython-input-22-fd8c7f39aa50> in <module>()----> 1 b.nationalityAttributeError: 'test' object has no attribute 'nationality'

len

len(s) 返回集合长度  
>>> print len(range(10))10

locals & globals

locals 是只读的,globals不是这两个函数主要提供基于字典的访问局部和全局变量的方式。在理解这两个函数时,首先来理解一下python中的名字空间概念。Python使用叫做命名空间的东西来记录变量的轨迹。命名空间只是一个字典,它的键字就是变量名,字典的值就是那些变量的值。实际上,命名空间可以象Python的字典一样进行访问每个函数都有着自已的名字空间,叫做局部名字空间,它记录了函数的变量,包括函数的参数和局部定义的变量。每个模块拥有它自已的名字空间,叫做全局名字空间,它记录了模块的变量,包括函数、类、其它导入的模块、模块级的变量和常量。还有就是内置名字空间,任何模块均可访问它,它存放着内置的函数和异常。当一行代码要使用变量 x 的值时,Python会到所有可用的名字空间去查找变量,按照如下顺序:1.局部命名空间 - 特指当前函数或类的方法。如果函数定义了一个局部变量 x,Python将使用这个变量,然后停止搜索。2.全局命名空间 - 特指当前的模块。如果模块定义了一个名为 x 的变量,函数或类,Python将使用这个变量然后停止搜索。3.内置命名空间 - 对每个模块都是全局的。作为最后的尝试,Python将假设 x 是内置函数或变量。如果Python在这些名字空间找不到 x,它将放弃查找并引发一个 NameError 的异常,同时传递There is no variable named 'x' 这样一条信息。
>>> def foo(arg,a):   x = 1   y = 'xxxxx'   for i in range(10):      j = 1      k = 1   print locals()   print   print globals()>>> foo(1,2){'a': 2, 'i': 9, 'k': 1, 'j': 1, 'arg': 1, 'y': 'xxxxx', 'x': 1}{'a': <__main__.fooA instance at 0x0000000002D75588>, 'c': <__main__.fooC instance at 0x0000000002D7E448>, 'b': <__main__.fooB instance at 0x0000000002D753C8>, 'foo': <function foo at 0x0000000002ECC6D8>, '__builtins__': <module '__builtin__' (built-in)>, 'l': [6, 7, 8, 9], 'fooB': <class __main__.fooB at 0x0000000002E3E2E8>, '__package__': None, '__name__': '__main__', 'fooC': <class __main__.fooC at 0x0000000002E3E6A8>, '__doc__': None, 'fooA': <class __main__.fooA at 0x0000000002E3E288>}

map

map(function, iterable, ...)本函数是把函数对象function作为函数,iterable对象的每一项作为参数,然后进行计算后输出迭代子iterator。如果函数对象function可以输入多参数,那么后面可以跟多个可迭代的对象。多个迭代对象时,以最短的对象为运行结果的判断。
>>> x = range(10)>>> print list(map(hex,x))['0x0', '0x1', '0x2', '0x3', '0x4', '0x5', '0x6', '0x7', '0x8', '0x9']>>> print list(map(lambda y: y*2+1,x))[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]>>> print list(map(lambda y: y>3,x))[False, False, False, False, True, True, True, True, True, True]

memoryview

memoryview(obj) 本函数是返回对象obj的内存查看对象。 所谓内存查看对象,就是对象符合缓冲区协议的对象, 为了给别的代码使用缓冲区里的数据,而不必拷贝,就可以直接使用。
>>> v = memoryview(b'abc123')>>> print v[1]b>>> print v[0]a

next

next(iterator[, default]) 本函数是返回迭代子对象下一个元素的值,主要通过调用__next__()方法来实现的。 如果default参数有设置,当下一个元素不存在时,就返回default参数的值, 否则抛出异常StopIteration。
>>> l = range(4)>>> it = iter(l)>>> print next(it)0>>> print next(it)1>>> print next(it)2>>> print next(it)3>>> print next(it,4)4>>> print next(it,5)5

print

1.格式化输出整数

>>> strHello = "the length of (%s) is %d" %('Hello World',len('Hello World'))>>> print strHellothe length of (Hello World) is 11

2.格式化输出16制整数

#%x --- hex 十六进制#%d --- dec 十进制#%o --- oct 八进制>>> nHex = 0x20>>> print "nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex)nHex = 20,nDec = 32,nOct = 40

3.格式化输出浮点数(float)

>>> import math>>> #default>>> print "PI = %f"%math.piPI = 3.141593>>> #width = 10,precise = 3,align = left>>> print "PI = %10.3f"%math.piPI =      3.142>>> #width = 10,precise = 3,align = rigth>>> print "PI = %-10.3f" % math.piPI = 3.142     >>> #前面填充字符>>> print "PI = %06d" % int(math.pi)PI = 000003>>> #显示正负号>>> print '%+f'% math.pi+3.141593>>> print(format(math.pi,'6.2f'))  3.14>>> print(format(math.pi,'6f'))3.141593>>> print(format(math.pi,'15f'))       3.141593>>> print(format(math.pi,'6.0f'))     3>>> print(format(math.pi,'6%'))314.159265%

4.格式化输出字符串(string)

>>> #precise = 3>>> print "%.3s " % ("jcodeer")jco >>> #precise = 4>>> print "%.*s" % (4,"jcodeer")jcod>>> #width = 10,precise = 3>>> print "%10.3s" % ("jcodeer")       jco

5.输出列表(list)

>>> l = [1,2,3,4,'jcodeer']>>> print l[1, 2, 3, 4, 'jcodeer']
'''6.出字典(dictionary)'''>>> d = {1:'A',2:'B',3:'C',4:'D'}>>> print d{1: 'A', 2: 'B', 3: 'C', 4: 'D'}

6.python print自动换行

print 会自动在行末加上回车,如果不需回车,只需在print语句的结尾添加一个逗号”,“,就可以改变它的行为。

>>> for i in range(0,5):        print i01234>>> for i in range(0,5):        print i,0 1 2 3 4

或直接使用下面的函数进行输出:

>>> import sys>>> sys.stdout.write('Hello World')Hello World

7. 万能的 %r

%r是一个万能的格式符,它会将后面给的参数原样打印出来,带有类型信息。

>>> formatter = "%r %r %r %r">>> print formatter % (1, 2, 3, 4)1 2 3 4>>> print formatter % ("one", "two", "three", "four")'one' 'two' 'three' 'four'>>> print formatter % (True, False, False, True)True False False True>>> print formatter % (formatter, formatter, formatter, formatter)'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'>>> print formatter % ("I had this thing.","That you could type up right.", "But it didn't sing.", "So I said goodnight." )'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

8.print语句输出包含转义字符的字符串的处理方法

>>> print "I'm OK"I'm OK>>> print 'Learn "Python" in imooc'Learn "Python" in imooc>>> print 'Bob said \"I\'m OK\".'Bob said "I'm OK".>>> s = 'Python was started in 1989 by \"Guido\".\nPython is free and easy to learn.'>>> s'Python was started in 1989 by "Guido".\nPython is free and easy to learn.'>>> print sPython was started in 1989 by "Guido".Python is free and easy to learn.>>> print r'''"To be, or not to be": that is the question.Whether it's nobler in the mind to suffer.'''"To be, or not to be": that is the question.Whether it's nobler in the mind to suffer.

9.print语句输出包含中文字符的字符串的处理方法

>>> print u'''静夜思... 床前明月光,... 疑是地上霜。... 举头望明月,... 低头思故乡。'''静夜思床前明月光,疑是地上霜。举头望明月,低头思故乡。

10.输出类似10000L的字符串类型

>>> print(format(math.pi,'6%'))314.159265%>>> print repr('hello,world!')'hello,world!'>>> print repr(10000L)10000L>>> print str('hello,world!')hello,world!>>> print str(10000L)10000

11.Python3.x中的print 函数

到3.x时print语句没有了,取而代之的是print()函数。 Python 2.6与2.7部分地支持这种形式的print语法。在Python 2.6与Python 2.7里面,以下四种形式是等价的:

>>> print 'fish'fish>>> print "fish"fish>>> print ("fish")fish>>> print("fish")fish

然而吉多有一个时光机:

>>> from __future__ import print_function>>> print("numpy","pandas",'scipy','matplotlib',sep='_')numpy_pandas_scipy_matplotlib

reduce

reduce(function, iterable[, initializer])reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。当initializer为非空时作为一个参数和iterable的第一个元素传递给function
def reduce(function, iterable, initializer=None):   it = iter(iterable)   if initializer is None:       try:           initializer = next(it)       except StopIteration:           raise TypeError('reduce() of empty sequence with no initial value')   accum_value = initializer   for x in iterable:       accum_value = function(accum_value, x)   return accum_value
>>> lst = range(1,6)>>> reduce(lambda x,y:x+y,lst)15>>> reduce(lambda x,y:x+y,lst,10)25

reload

reload(module)对已经加载的模块进行重新加载,一般用于原模块有变化等特殊情况,reload前该模块必须已经import过。e.g:import osreload(os)说明:reload会重新加载已加载的模块,但原来已经使用的实例还是会使用旧的模块,而新生产的实例会使用新的模块;reload后还是用原来的内存地址;不能支持from。。import。。格式的模块进行重新加载。
#A.pyimport osprint 'in a',id(os)
#encoding: utf-8  import A  #第一次会打印A里面的语句  print id(A)    #原来A的内存地址import os  #再次导入os后,其内存地址和A里面的是一样的,因此这里只是对os的本地引用  print 'in c',id(os)  import A  #第二次不会打印A里面的语句,因为没有重新加载  reload(A)   #第二次reload还会打印A里面的语句,因为有重新加载  print id(A) #reload后A的内存地址,和原来一样
in a 3459700039168664in c 34597000in a 3459700039168664[Finished in 0.2s]

在特殊情况的下才会使用reload函数;
除了原来模块文件有修改外,还有哪些情况需要使用reload函数呢,这里举个例子:

#encoding: utf-8  import sys     sys.setdefaultencoding('utf8')
Traceback (most recent call last):  File "D:\M.py", line 3, in <module>    sys.setdefaultencoding('utf8')AttributeError: 'module' object has no attribute 'setdefaultencoding'[Finished in 0.2s with exit code 1]
#encoding: utf-8  import sys    reload(sys)   sys.setdefaultencoding('utf8')    del sys.setdefaultencoding   ##删除原来的setdefaultencoding函数     sys.setdefaultencoding('gb2312')  
Traceback (most recent call last):  File "D:\M.py", line 6, in <module>    sys.setdefaultencoding('gb2312')  AttributeError: 'module' object has no attribute 'setdefaultencoding'[Finished in 0.2s with exit code 1]

上面的测试会失败,那么为什么要在调用setdefaultencoding时必须要先reload一次sys模块呢?
因为这里的import语句其实并不是sys的第一次导入语句,
也就是说这里其实可能是第二、三次进行sys模块的import,
这里只是一个对sys的引用,只能reload才能进行重新加载;
那么为什么要重新加载,而直接引用过来则不能调用该函数呢?
因为setdefaultencoding函数在被系统调用后被删除了,
所以通过import引用进来时其实已经没有了,
所以必须reload一次sys模块,这样setdefaultencoding才会为可用:

#encoding: utf-8  import sys   #引用sys模块进来,并不是进行sys的第一次加载  reload(sys)  #重新加载sys  sys.setdefaultencoding('utf8')  ##调用setdefaultencoding函数  
[Finished in 0.2s]

那么到底是谁在之前就导入sys并且调用了setdefaultencoding函数呢?
答案就在python安装目录的Lib文件夹下,有一个叫site.py.

Lib/site.py
Lib/site.py

site.py的DocString说明该脚本是为了在sys.path中加入第三方模块
并会在每次启动python.exe进行Initialization时加载site.py
site.py的DocString

从下方的截图可以看出site.py一开始就已经import sys
site.py一开始就已经import sys

在site.py的setencoding函数中使用了setdefaultencoding函数
并且设置默认的编码方式为‘ASCII’
在site.py的setencoding函数中使用了setdefaultencoding函数

在main函数中调用setencoding函数后del属性setdefaultencoding
在main函数中调用setencoding函数后del属性setdefaultencoding
所以在windows下进行python2的编程时时常遇到编码为‘ascii’,不能对中文字符进行解码的问题
在遇到此类问题,必要的情况下可以使用reload重新调入sys,对当前的编码环境重新进行设置

repr & str

repr(object) & str(object)变量值被转换为字符串的两种机制:前者的目标是准确性,后者的目标是可读性
repr(object)返回一个表示对象的可打印的字符串。这和通过转换(反引号``)处理得到的结果一致。作为一个普通函数,可以使用这个运算有些时候是有用处的。对于大部分类型,这个函数尝试返回一个字符串,当其传给eval(),将生成同样的对象,(即eval(repr(object)==object.)否则生成一个用尖括号括起来的字符串,包含着对象类型名和通常一些对象名以及对象地址等额外信息。一个类可以通过重新定义__repr__()成员函数来控制自身实例关于这个函数的返回值。
str(object)返回一个表示对象的可打印的友好的字符串。对于字符串来说,将返回自身。与repr(object)区别在于,str(object)不尝试返回一个传递给eval()的字符串;其目标是返回一个可打印的字符串。如果没有给出参数,返回空字符串(同理对类,可通过__str__()成员控制其行为)
>>> print repr("hello world!")'hello world!'>>> print repr(10000L)10000L>>> print str("hello world!")hello world!>>> print str(10000L)10000>>> temp = 42>>> print "the temperature is "+tempTraceback (most recent call last):  File "<pyshell#18>", line 1, in <module>    print "the temperature is "+tempTypeError: cannot concatenate 'str' and 'int' objects>>> print "the temperature is "+ `temp`the temperature is 42>>> print "the temperature is " + repr(temp)the temperature is 42

slice

slice()本函数是实现切片对象,主要用在切片操作函数里的参数传递。
>>> myslice = slice(5)>>> print mysliceslice(None, 5, None)>>> l = range(10)>>> print l[myslice][0, 1, 2, 3, 4]>>> myslice = slice(1,10,2)>>> print l[myslice][1, 3, 5, 7, 9]

super

super(type[, object-or-type])  1. super并不是一个函数,是一个类名,形如super(B, self)事实上调用了super类的初始化函数,产生了一个super对象;  2. super类的初始化函数并没有做什么特殊的操作,只是简单记录了类类型和具体实例;  3. super(B, self).func的调用并不是用于调用当前类的父类的func函数;  4. Python的多继承类是通过mro的方式来保证各个父类的函数被逐一调用,而且保证每个父类函数只调用一次(如果每个类都使用super);  5. 混用super类和非绑定的函数是一个危险行为,这可能导致应该调用的父类函数没有调用或者一       个父类函数被调用多次。
      (OBJECT)      |     |      |     A      |   / |      |  /  |      B C   |       \|   D          E   |         \  |          \ |            F
class A(object):   def __init__(self):         print "enter A"         print "leave A"class B(object):   def __init__(self):         print "enter B"         print "leave B"class C(A):   def __init__(self):         print "enter C"         super(C, self).__init__()         print "leave C"class D(A):   def __init__(self):         print "enter D"         super(D, self).__init__()         print "leave D"class E(B, C):   def __init__(self):         print "enter E"         B.__init__(self)         C.__init__(self)         print "leave E"class F(E, D):   def __init__(self):         print "enter F"         E.__init__(self)         D.__init__(self)         print "leave F"f = F()
enter Fenter Eenter Bleave Benter Center Denter Aleave Aleave Dleave Cleave Eenter Denter Aleave Aleave Dleave F[Finished in 0.2s]
class A(object):   def __init__(self):         print "enter A"         super(A, self).__init__()  # new         print "leave A"class B(object):   def __init__(self):         print "enter B"         super(B, self).__init__()  # new         print "leave B"class C(A):   def __init__(self):         print "enter C"         super(C, self).__init__()         print "leave C"class D(A):   def __init__(self):         print "enter D"         super(D, self).__init__()         print "leave D"class E(B, C):   def __init__(self):         print "enter E"         super(E, self).__init__()  # change         print "leave E"class F(E, D):   def __init__(self):         print "enter F"         super(F, self).__init__()  # change         print "leave F"f = F()
enter Fenter Eenter Benter Center Denter Aleave Aleave Dleave Cleave Bleave Eleave F[Finished in 0.2s]
class Person(object):    def __init__(self, name, gender):        self.name = name        self.gender = genderclass Educator(object):    def __init__(self,course):        self.course = courseclass Teacher(Person,Educator):   def __init__(self,name,gender,course):      Person.__init__(self,name,gender)      Educator.__init__(self,course)t = Teacher('Alice', 'Female', 'English')print t.nameprint t.course
AliceEnglish[Finished in 0.2s]

type

type(object) 返回该object的类型  
>>> type(range(5))<type 'list'>>>> type(dict())<type 'dict'>>>> type(tuple(range(5)))<type 'tuple'>>>> type(1)<type 'int'>>>> type('hello')<type 'str'>>>> type(type(1))<type 'type'>

vars

vars([object])本函数是实现返回对象object的属性和属性值的字典对象。如果默认不输入参数,就打印当前调用位置的属性和属性值,相当于locals()的功能。如果有参数输入,就只打印这个参数相应的属性和属性值。
>>> print vars(){'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}>>> class foo:   a = 1>>> print vars(foo){'a': 1, '__module__': '__main__', '__doc__': None}>>> foo = foo()>>> print vars(foo){}

zip

zip([iterable, …])
本函数是实现从多个序列生一个元组列表迭代子返回,
即是从每个序列里获取一项,然后把所有的项生成元组,再把这些元组生成列表返回。
如果有多个序列,以最短的序列为元组的个数。
如果在参数前面添加*表示反向处理,即是从元组列表转换为分离的列表返回。

```python>>> l = [1,2,3]>>> x = [4,5,6]>>> print(list(zip(l, x)))[(1, 4), (2, 5), (3, 6)]>>> x = [4,5]>>> print(list(zip(l, x)))[(1, 4), (2, 5)]>>> y = (7, 8, 9)>>> print(list(zip(l, x, y)))[(1, 4, 7), (2, 5, 8)]>>> lxy = list(zip(l, x, y))>>> print(list(zip(*lxy)))[(1, 2), (4, 5), (7, 8)]
1 0