Python标准模块--built-ins函数

MelvinaCalv 8年前
   <h2><strong>1.Python内置函数</strong></h2>    <p><img src="https://simg.open-open.com/show/579feddb61c984b2a7e41b70bc47bd24.png"></p>    <h2><strong>2.Python内置函数举例</strong></h2>    <h3><strong>2.1 数学运算</strong></h3>    <p>abs,计算绝对值;</p>    <pre>  <code class="language-python">>>> abs(-1)  1  >>> abs(3)  3</code></pre>    <p>round,四舍五入;</p>    <pre>  <code class="language-python">>>> round(2.9)  3.0  >>> round(2.45)  2.0  >>> round(-1.2)  -1.0  >>> round(-1.6)  -2.0</code></pre>    <p>pow,计算幂;</p>    <pre>  <code class="language-python">>>> pow(2,3)#2**3  8  >>> pow(2,3,5)#2**3%5  3</code></pre>    <p>cmp,比较两个数大小,返回0,表示相等,返回-1;表示左边数值小于右边数值;返回1,表示左边数值大于右边数值;</p>    <pre>  <code class="language-python">>>> cmp(2.3,2.3)  0  >>> cmp(2.3,2.4)  -1  >>> cmp(2.3,2.2)  1</code></pre>    <p>divmod,返回除法的结果和余数;</p>    <pre>  <code class="language-python">>>> divmod(9,4)  (2, 1)  >>> divmod(9,3)  (3, 0)</code></pre>    <p>max,求最大值;</p>    <pre>  <code class="language-python">>>> max([1,2,3,-1,0])  3</code></pre>    <p>min,求最小值;</p>    <pre>  <code class="language-python">>>> min([1,2,3,-1,0])  -1</code></pre>    <p>sum,求和;</p>    <pre>  <code class="language-python">>>> sum([1,2,3,4,5])  15</code></pre>    <h3><strong>2.2 类型转换</strong></h3>    <p>int,转换为整数,integer;</p>    <pre>  <code class="language-python">>>> int("32")  32  >>> int("-2")  -2  >>> int("-1.2")  Traceback (most recent call last):    File "<input>", line 1, in <module>      int("-1.2")  ValueError: invalid literal for int() with base 10: '-1.2'</code></pre>    <p>float,转换为浮点型,float;</p>    <pre>  <code class="language-python">>>> float("-1.2")  -1.2  >>> float("-1.20")  -1.2  >>> float("-0.3")  -0.3  >>> float("1")  1.0</code></pre>    <p>long,转换为长整型,long integer;</p>    <pre>  <code class="language-python">>>> long("1234567890")  1234567890L</code></pre>    <p>str,转换为字符串类型,string;</p>    <pre>  <code class="language-python">>>> str(123)  '123'</code></pre>    <p>complex,转换为复数类型;</p>    <pre>  <code class="language-python">>>> complex(3,2)  (3+2j)</code></pre>    <p>ord,转换为字符对应的数值;</p>    <pre>  <code class="language-python">>>> ord('a')  97</code></pre>    <p>chr,转换为字符对应的数值;</p>    <pre>  <code class="language-python">>>> chr(97)  'a'</code></pre>    <p>unichr,转换为数值对应的unicode字符;</p>    <pre>  <code class="language-python">>>> unichr(97)  u'a'</code></pre>    <p>bool,转换为相应的真假值;</p>    <pre>  <code class="language-python">>>> bool(0)  False  >>> bool(1)  True</code></pre>    <p>bin,返回一个字符串,表示一个数值的二进制数;</p>    <pre>  <code class="language-python">>>> bin(31)  '0b11111'</code></pre>    <p>hex,返回一个字符串,表示一个一个数值的十六进制数;</p>    <pre>  <code class="language-python">>>> hex(31)  '0x1f'</code></pre>    <p>oct,返回一个字符串,表示一个数值的八进制数;</p>    <pre>  <code class="language-python">>>> oct(31)  '037'</code></pre>    <p>list,转换为列表;</p>    <pre>  <code class="language-python">>>> list((1,2,3,4))  [1, 2, 3, 4]</code></pre>    <p>tuple,转换为定值表;</p>    <pre>  <code class="language-python">>>> tuple([1,2,3,4])  (1, 2, 3, 4)</code></pre>    <p>slice,构建下标对象;</p>    <pre>  <code class="language-python">>>> a = [1,2,3,4,5]  >>> slices = slice(0,4,2)  >>> a[slices]  [1, 3]</code></pre>    <p>dict,构建词典;</p>    <pre>  <code class="language-python">>>> dict(a=1,b=[1,2],c='hello')  {'a': 1, 'c': 'hello', 'b': [1, 2]}</code></pre>    <h3><strong>2.3 序列操作</strong></h3>    <p>all,所有元素都相当与True;</p>    <pre>  <code class="language-python">>>> a = range(0,4)  >>> b = range(1,4)  >>> a  [0, 1, 2, 3]  >>> b  [1, 2, 3]  >>> all(a)  False  >>> all(b)  True</code></pre>    <p>any,是否有任意一个元素相当于True;</p>    <pre>  <code class="language-python">>>> a = [0]  >>> b = range(0,4)  >>> a  [0]  >>> b  [0, 1, 2, 3]  >>> any(a)  False  >>> any(b)  True</code></pre>    <p>sorted,返回排序后的序列,默认是递增序列,如果指定reverse为True,则返回递减序列;</p>    <pre>  <code class="language-python">>>> a = [1,4,3,2]  >>> sorted(a)  [1, 2, 3, 4]  >>> sorted(a,reverse=False)  [1, 2, 3, 4]  >>> sorted(a,reverse=True)  [4, 3, 2, 1]</code></pre>    <p>reversed,返回反序的序列;</p>    <pre>  <code class="language-python">>>> a = [1,4,3,2]  >>> b = [ele for ele in reversed(a)]  >>> b  [2, 3, 4, 1]</code></pre>    <h3><strong>2.4 类,对象,属性</strong></h3>    <p>hasattr,检查对象是否拥有某个属性;</p>    <p>getattr,返回某属性;</p>    <p>setattr,将对象中的属性设置为新的属性;</p>    <p>delattr,删除对象中的属性;</p>    <p>isinstance,判断对象是否为类生成的对象;</p>    <p>issubclass,判断类是否为某类的子类;</p>    <pre>  <code class="language-python">class A(object):      def __init__(self):          # 定义属性value          self.value = [2,3,0]          # 定义属性min,为built-in中的min函数          self.min = min        def getValue(self):          return self.value      def minValue(self):          return self.min(self.value)    # 定义对象Aobject  Aobject = A()  # 获取Aobject所有的属性  print dir(Aobject)  # ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'getValue', 'min', 'minValue', 'value']      # 判断Aobject是否有value属性  print hasattr(Aobject,"value")  # True  # 获取Aobject的vallue属性  print getattr(Aobject,"value")  # [2, 3, 0]  # 将Aobject的min属性修改为max  setattr(Aobject,"min",max)  # 调用minValue,将会返回列表的最大值  print Aobject.minValue()  # 3    # 删除Aobject的value属性  delattr(Aobject,"value")  # 判断Aobject是否有value属性  print hasattr(Aobject,"value")  # False    # 判断Aobject是否为类A的实例  print isinstance(Aobject,A)  # True  # 判断A是否为object的子类  print issubclass(A,object)  # True</code></pre>    <h3><strong>2.5 编译,执行</strong></h3>    <p>repr,返回对象的字符串表达式;</p>    <pre>  <code class="language-python">class A(object):      def __init__(self):          # 定义属性value          self.value = [2,3,0]          # 定义属性min,为built-in中的min函数          self.min = min        def getValue(self):          return self.value      def minValue(self):          return self.min(self.value)      # 定义对象Aobject  Aobject = A()  b = repr(Aobject)  print b</code></pre>    <p>compile,编译字符串成为code对象;</p>    <pre>  <code class="language-python">testCode = compile("for i in range(10): print i,","",'exec')  exec testCode    print ""  testCode2 = compile("3 * 4 + 5",'','eval')  print eval(testCode2)</code></pre>    <p>eval,解释字符串表达式,参数也可以是compile()返回的code对象;</p>    <pre>  <code class="language-python">>>> eval("1+3")  4</code></pre>    <p>exec,解释并执行字符串,参数也可以是compile()返回的code对象;</p>    <pre>  <code class="language-python">>>> exec("print ('hello world')")  hello world</code></pre>    <h3><strong>2.6 其它</strong></h3>    <p>input,等待输入;</p>    <p>raw_input,等待输入;</p>    <pre>  <code class="language-python">>>> input("please input:")  please input:"sting"  'sting'  >>> raw_input("please input:")  please input:string  u'string'</code></pre>    <p>raw_input()直接读取控制台的输入(任何类型的的输入它都可以接收);</p>    <p>input(),希望能够读取一个合法的python表达式,即你输入字符串的时候,必须使用引号将它括起来,否则会引发一个SyntaxError。</p>    <p>input()本质上还是使用raw_input()函数来实现,只是调用完raw_input()之后,在调用eval()函数,所以,你甚至可以将表达式作为input()的参数,并且它会计算表达式的值并返回它。</p>    <p>除非对input()有特别需要,否则一般情况下我们都是推荐使用raw_input()来与用户交互。</p>    <p>例如,</p>    <pre>  <code class="language-python">>>> raw_input("please:")  please:1+2  '1+2'  >>> input("please:")  please:1+2  3  >>> raw_input("please:")  please:'a'  "'a'"  >>> input("please:")  please:'a'  'a'  >>> raw_input("please:")  please:  ''  >>> input("please:")  please:  Traceback (most recent call last):    File "<input>", line 1, in <module>    File "<string>", line 0            ^  SyntaxError: unexpected EOF while parsing</code></pre>    <p>globals,返回全局命名空间,比如全局变量名,全局函数名;</p>    <p>locals,返回局部命名空间;</p>    <h2><strong>3.Reference</strong></h2>    <p><a href="/misc/goto?guid=4959671457728430906" rel="nofollow,noindex">2. Built-in Functions</a></p>    <p><a href="/misc/goto?guid=4959725086349786630" rel="nofollow,noindex">python函数: 内置函数</a></p>    <p> </p>    <p>来自:http://www.cnblogs.com/zhbzz2007/p/6058634.html</p>    <p> </p>