晓夏

YoungCheung

Zhang Sir's technical way

python内置函数详解

浏览量:1172

Python解释器有许多内置的功能和类型,始终可用。他们按字母顺序列在这里。

blob.png

下面我们依次了解内置函数:

⚠️注意:不重要的我们下面将会省略

abs (x)

       返回一个函数的绝对值,参数可以是整数或浮点数。

>>> abs(100)
100
>>> abs(-100)
100

all(iterable)

       返回True如果的所有元素迭代真实的(或者如果可迭代为空)

>>> all([1,2,3])
True

any(iterable)

       返回True如果任何元素迭代是真实的。如果iterable为空,则返回False  

>>> any([1,2,3])
True
>>> any([])
False

bin(x)

        将整数转换为二进制字符串。结果是一个有效的Python表达式。如果x不是Python int对象,则必须定义一个__index__()返回整数的 方法。

>>> bin(100)
'0b1100100'

bool(x)

     判断x是否是布尔类型,返回True或者False

>>> bool(2)
True

class bytearray([source[, encoding[, errors]]])

返回一个新的字节数组。的bytearray类是整数的范围为0 <= X一个可变的序列<256它具有最的可变序列,在所描述的常规方法的可变序列类型,以及大多数方法,该bytes类型已见字节和ByteArray操作。

可选的源参数可用于以几种不同的方式初始化数组:

如果是字符串,还必须给出编码(和可选的 错误)参数; bytearray()然后使用字符串转换为字节str.encode()。

如果它是整数,则数组将具有该大小,并且将以空字节初始化。

如果是符合缓冲区接口的对象,则将使用对象的只读缓冲区来初始化字节数组。

如果它是一个可迭代的,它必须是范围内的整数的迭代 ,它们被用作数组的初始内容。0 <= x < 256

没有参数,将创建一个大小为0的数组。

>>> a = bytearray(3)
>>> a
bytearray(b'\x00\x00\x00')
>>> a[0]
  
>>> a[1]
  
>>> a[2]
  
>>> b = bytearray("abc")
>>> b
bytearray(b'abc')
>>> b[0]
   
>>> b[1]
  
>>> b[2]
  
>>> c = bytearray([1, 2, 3])
>>> c
bytearray(b'\x01\x02\x03')
>>> c[0]
  
>>> c[1]
  
>>> c[2]
  
>>> d = bytearray(buffer("abc"))
>>> d
bytearray(b'abc')
>>> d[0]
  
>>> d[1]

>>> d[2]

bytes(x)

     将x转化为bytes类型

>>> bytes(1)
b'\x00'

callable(object)

    检查对象object是否能被调用

        1、类是可以被调用的
        2、实例是不可以被调用的,除非类中声明了__call__方法

>> 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)

chr(x)

        返回整数i对应的ASCII字符。与ord()作用相反。参数x:取值范围[0, 255]之间的正数。

>>> chr(97)
'a'
>>> chr(98)
'b'
>>> ord('a')
97
>>> ord('b')
98

classmethod(function)

        classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

类方法既可以直接类调用(C.f()),也可以进行实例调用(C().f())。

>>> class C:
...     @classmethod
...     def f(self):
...             print "This is a class method"
...
>>> C.f()
This is a class method
>>> c = C()
>>> c.f()
This is a class method
>>> class D:
...     def f(self):
...             print " This is not a class method "
...
>>> D.f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
>>> d = D()
>>> d.f()
This is not a class method

compile(source, filename, mode[, flags[, dont_inherit]])

        将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

        参数source:字符串或者AST(Abstract Syntax Trees)对象。

        参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。

        参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。

        参数flag和dont_inherit:这两个参数暂不介绍,可选参数。

>>> code = "for i in range(0, 10): print i"
>>> cmpcode = compile(code, '', 'exec')
>>> exec cmpcode
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

complex([real[, imag]])

          创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

                参数real: int, long, float或字符串;

                参数imag: int, long, float。

>>> complex(1, 2)
(1 + 2j)
#数字
>>> complex(1)
(1 + 0j)
#当做字符串处理
>>> complex("1")
(1 + 0j)
#注意:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex("1+2j")
(1 + 2j)

dir()

        不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

        参数object: 对象、变量、类型。

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import struct
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'struct']
>>> dir(struct)
['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']
>>> class Person(object):
...     def __dir__(self):
...             return ["name", "age", "country"]
...
>>> dir(Person)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> tom = Person()
>>> dir(tom)
['age', 'country', 'name']

delattr(object, name)

中文说明:删除object对象名为name的属性。这个函数的命名真是简单易懂啊,和jquery里面差不多,但是功能不一样哦,注意一下。

参数object:对象。

参数name:属性名称字符串。

>>> class Person:
...     def __init__(self, name, age):
...             self.name = name
...             self.age = age
...
>>> tom = Person("Tom", 35)
>>> dir(tom)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> delattr(tom, "age")
>>> dir(tom)
['__doc__', '__init__', '__module__', 'name']

divmod(a,b)

divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数

返回结果类型为tuple

参数:

a,b可以为数字(包括复数)

>>> divmod(9,2)
(4, 1)
>>> divmod(11,3)
(3, 2)
>>> divmod(1+2j,1+0.5j)
((1+0j), 1.5j)

enumerate()

        enumerate函数用于遍历序列中的元素以及它们的下标,多用于在for循环中得到计数,enumerate参数为可遍历的变量,如 字符串,列表等

        一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:

for i in range (0,len(list)): 
  print i ,list[i]

但是这种方法有些累赘,使用内置enumerrate函数会有更加直接,优美的做法,先看看enumerate的定义:

def enumerate(collection): 
  'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...'   
   i = 0 
   it = iter(collection) 
   while 1: 
   yield (i, it.next()) 
   i += 1
>>> list=['a','b','c','d']
>>> for i,e in enumerate(list):
...     print(i,e)
... 
0 a
1 b
2 c
3 d

eval()

        将字符串str当成有效的表达式来求值并返回计算结果。

        语法: eval(source[, globals[, locals]]) -> value

    参数:

    source:一个Python表达式或函数compile()返回的代码对象

    globals:可选。必须是dictionary

    locals:可选。任意map对象

可以把list,tuple,dict和string相互转化。
#################################################
字符串转换成列表
>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>>type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> type(b)
<type 'list'>
#################################################
字符串转换成字典
>>> a = "{1: 'a', 2: 'b'}"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
{1: 'a', 2: 'b'}
>>> type(b)
<type 'dict'>
#################################################
字符串转换成元组
>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> type(a)
<type 'str'>
>>> b = eval(a)
>>> print b
([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
>>> type(b)
<type 'tuple'>

exec()

        exec函数和eval函数类似,也是执行动态语句,只不过eval函数只用于执行表达式求值,而exec函数主要用于执行语句块。

>>> eval('a=1+2') #执行语句报错Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    eval('a=1+2')
  File "<string>", line 1
    a=1+2
     ^SyntaxError: invalid syntax
>>> exec('a=1+2') #执行语句
>>> a 
3

第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。

globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量

>>> g = {'num':2}
>>> type(g)
<class 'dict'>
>>> exec('num2 = num + 2',g)
>>> g['num']
2
>>> g['num2'] #收集了exec中定义的num2全局变量
4

 locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

>>> g = {'num':2}
>>> type(g)
<class 'dict'>
>>> l = {'num2':3}
>>> type(l)
<class 'dict'>
>>> exec('''
num2 = 13
num3 = num + num2
''',g,l)
>>> l['num2'] #l中num2值已经改变
13

为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

>>> g = {}
>>> exec('a = abs(-1)',g)
>>> 
>>> g = {'__builtins__':{}}
>>> exec('a = abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    exec('a = abs(-1)',g)
  File "<string>", line 1, in <module>
NameError: name 'abs' is not defined

当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。

>>> num = 1
>>> exec('num2 = num + 1')
>>> globals()
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'num2': 2, 'num': 1}
>>> 
>>> 
>>> exec('num2 = num + 1',{}) #指定了globals参数,globals中无num变量 执行失败
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    exec('num2 = num + 1',{})
  File "<string>", line 1, in <module>
NameError: name 'num' is not defined
>>> l = locals()
>>> l
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}
>>> 
>>> exec('num3 = num + 1',{},l)#指定了globals参数,globals中无num变量,指定了locals变量,locals变量含有num变量 执行成功
>>> l
{'__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, 'num3': 2, '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}
>>>

float(x)

        将x转为浮点数

>>> float(1)
1.0
>>> float(2)
2.0

format()

    强大的字符串格式化函数。自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足。那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱。

位置方法格式化:

>>> '{}.{}'.format('pythontab', 'com')
'pythontab.com'
>>> '{}.{}.{}'.format('www', 'pythontab', 'com')
'www.pythontab.com'
>>> '{1}.{2}'.format('www', 'pythontab', 'com')
'pythontab.com'
>>> '{1}.{2} | {0}.{1}.{2}'.format('www', 'pythontab', 'com')
'pythontab.com | www.pythontab.com'

字符串的format函数可以接受不限个参数,参数位置可以不按顺序,参数可以不使用或者使用多次,非常灵活

⚠️注意: python2.6下不能为空{},python2.7以上版本可以。

通过关键字参数:

>>> '{domain}, {year}'.format(domain='www.pythontab.com', year=2016)
'www.pythontab.com, 2016'
>>> '{domain} ### {year}'.format(domain='www.pythontab.com', year=2016)
'www.pythontab.com ### 2016'
>>> '{domain} ### {year}'.format(year=2016,domain='www.pythontab.com')
'www.pythontab.com ### 2016'

通过对象属性:

>>> class website: 
        def __init__(self,name,type): 
            self.name,self.type = name,type 
        def __str__(self): 
          return 'Website name: {self.name}, Website type: {self.type} '.format(self=self) 
>>> print str(website('pythontab.com', 'python'))
Website name: pythontab.com, Website type: python
>>> print website('pythontab.com', 'python')
Website name: pythontab.com, Website type: python

通过下标:

>>> '{0[1]}.{0[0]}.{1}'.format(['pyhtontab', 'www'], 'com')
'www.pyhtontab.com'

有了这些便捷的“映射”方式,我们就有了偷懒利器。基本的python知识告诉我们,list和tuple可以通过“打散”成普通参数给函数,而dict可以打散成关键字参数给函数(通过和*)。所以可以轻松的传个list/tuple/dict给format函数, 非常灵活。

格式限定符:

    它有着丰富的的“格式限定符”(语法是{}中带:号),比如:

    填充与对齐

    填充常跟对齐一起使用

    ^、<、>分别是居中、左对齐、右对齐,后面带宽度

    :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

>>> '{:>10}'.format(2016)
'      2016'
>>> '{:#>10}'.format(2016)
'######2016'
>>> '{:0>10}'.format(2016)
'0000002016'

数字精度与类型f

精度常跟类型f一起使用

>>> '{:.2f}'.format(2016.0721)
'2016.07'

其中.2表示长度为2的精度,f表示float类型。

其他类型

主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。

>>> '{:b}'.format(2016)
'11111100000'
>>> '{:d}'.format(2016)
'2016'
>>> '{:o}'.format(2016)
'3740'
>>> '{:x}'.format(2016)
'7e0'
>>>

用逗号还能做金额的千分位分割符

>>> '{:,}'.format(20160721)
'20,160,721'

frozenset()

        本函数是返回一个冻结的集合。所谓冻结就是这个集合不能再添加或删除任何集合里的元素。因此与集合set的区别,就是set是可以添加或删除元素,而frozenset不行。frozenset的主要作用就是速度快,它是使用hash算法实现。参数iterable是表示可迭代的对象,比如列表、字典、元组等等。

>>> l = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]  
>>> print(len(l), l)  
11 [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9]
>>> set = frozenset(l)  
>>> print(len(set), set)  
9 frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})

getattr()

class A:
    def __init__(self):
        self.a = 'a'

    def method(self):
        print
        "method print"
a = A()
print(getattr(a, 'a', 'default'))  # 如果有属性a则打印a,否则打印default
print(getattr(a, 'b', 'default') ) # 如果有属性b则打印b,否则打印default
print(getattr(a, 'method', 'default'))# 如果有方法method,否则打印其地址,否则打印default
print(getattr(a, 'method', 'default')())# 如果有方法method,运行函数并打印None否则打印default

注:使用getattr可以轻松实现工厂模式。 
例:一个模块支持html、text、xml等格式的打印,根据传入的formate参数的不同,调用不同的函数实现几种格式的输出

import statsout 
def output(data, format="text"):                           
    output_function = getattr(statsout, "output_%s" %format) 
    return output_function(data)

globals()

        返回表示当前全局符号表的字典

#globals()
#说明:在当前作用域下,查看全局变量
'''
globals(...)
    globals() -> dictionary
    
    Return the dictionary containing the current scope's global variables.
'''
#案例
b='zhangyang'
print globals#<built-in function globals>
print globals()
'''
{
'b': 'zhangyang',
'__builtins__': <module '__builtin__' (built-in)>,
'__file__': 'C:\\Users\\Administrator\\Desktop\\Test\\Test.py',
'__package__': None,
'__name__': '__main__',
'__doc__': "\nglobals(...)\n    globals() -> dictionary\n    \n    Return the dictionary containing the current scope's global variables.\n"
}
'''

hasattr(object, name)

        判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。

        需要注意的是name要用括号括起来

>>> class test():
...     name="zhangyang"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> hasattr(t, "name") #判断对象有name属性
True
>>> hasattr(t, "run")  #判断对象有run方法
True
>>>

hash(object)

         本函数返回对象的哈希值。返回的哈希值是使用一个整数表示,通常使用在字典里,以便实现快速查询键值。参数object输入是数字类型时,是根据数值来计算的,比如1和1.0计算出来是一样的哈希值,因此说这个函数是不区分不同的数值类型。

>>> hash('abc')
-1645391281322227936
>>> hash(1)
1

help()

      help()函数是查看函数或模块用途的详细说明,而dir()函数是查看函数或模块内的操作方法都有什么,输出的是方法列表。

help(dir)

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

id(object)

        本函数是返回对象object的标识符,标识符类型为整数,在同一个时间里所有对象的标识符是唯一的,如果在不同生命周期的对象有可能有相同的标识符。比如创建对象A之后,再删除A,再创建对象B,对象A与对象B可能有相同的标识符。在CPython里的实现算法是直接返回对象所在内存地址。

#id()  
name1 = 'abc'  
name2 = 'cde'  
print(id(name1))  
print(id(name2))  
print(id([]))

输出:

5472640
36108384
36127048

input([prompt])

获取用户输入,推荐使用raw_input,因为该函数将不会捕获用户的错误输入

user_input=input('please input your name:')

int[x[,base]]

    将一个字符转换为int类型,base表示进制,注意,如要指定进制的,则输入值要与指定进制是同一类型,而不是输入值转化为指定进制的意思

>>> int("10",2)
2

isinsance(object, class-or-type-or-tuple) ->bool

        内置函数isinstance有两个参数,第一个参数是待检测的对象,第二个参数是对象类型,可以是单个类型,也可以是元组,返回的bool类型,如果待检测对象属于第二个参数,则返回True;否则,返回False

>>> isinstance('abc',(str,float,int))
True
>>> isinstance(123,str)
False

issubclass(class, classinfo)

        本函数用来判断类参数class是否是类型参数classinfo的子类。

class Line:  
    pass  
class RedLine(Line):  
    pass  
      
class Rect:  
    pass  
      
print(issubclass(RedLine, Line))  
print(issubclass(Rect, Line))

输出结果

Ture
False

iter(object, sentinel)

        Python官方文档对于这种形式的解释是:“ If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel,StopIteration will be raised, otherwise the value will be returned.”。

这句话的意思是说:如果传递了第二个参数,则object必须是一个可调用的对象(如,函数)。此时,iter创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用object。  如果__next__的返回值等于sentinel,则抛出StopIteration异常,否则返回下一个值。

class counter:
 
     def __init__(self, _start, _end):
         self.start = _start
         self.end = _end
 
     def get_next(self):
         s = self.start
         if(self.start < self.end):
             self.start += 1
         else:
             raise StopIteration
 
         return s
 
 
 c = counter(1, 5)
 iterator = iter(c.get_next, 3)
 print(type(iterator))
 for i in iterator:
     print(i)

输出结果:

<class 'callable_iterator'>
1
2

len()

>>> len('adsfghj')
7

list()

list.append(x) 

在列表的尾部添加一个项,等价于 a[len(a):] = [x]。

list.extend(L) 

将给定的列表L接到当前列表后面,等价于 a[len(a):] = L。

list.insert(i, x) 

在给定的位置 i 前插入项,例如:a.insert(0, x) 会在列表的头部插入,而 a.insert(len(a), x) 则等价于 a.append(x)。

list.remove(x) 

移除列表中第一个值为 x 的项,没有的话会产生一个错误。

list.pop([i]) 

删除列表给定位置的项,并返回它。如果没指定索引,a.pop()移除并返回列表最后一项。(方括号表示可选)

list.clear()

删除列表中的所有项,相当于 del a[:]。

list.index(x)

返回列表中第一个值为 x 的项的索引。如果没有匹配的项, 则产生一个错误。

list.count(x)

返回列表中 x 出现的次数。

list.sort()

就地完成列表排序。

list.reverse()

就地完成列表项的翻转。

list.copy()

返回列表的一个浅拷贝,相当于a[:]。

注:tuple、dict等都有它们自己的方法,可以使用dir()和help()查询。

locals()

    # 返回一个字典,包括所有的局部变量与它的值所组成的键值对

def foo(arg, a):
    x = 100
    y = 'hello python!'
    for i in range(10):    
        j = 1
        k = i
    print(locals())
    
foo(1,2)

输出

{'y': 'hello python!', 'k': 9, 'arg': 1, 'j': 1, 'i': 9, 'a': 2, 'x': 100}

map()(函数或lambda表达式,可迭代的对象) 

         #对可迭代的每一个元素,将其作为实参传入函数,将每一次调用函数返回的结果都添加到map的返回值中。

tuple(map(lambda a:a+1,(1,2,3))) 返回(2,3,4)

>>> map(lambda a:a+1,(1,2,3))
<map object at 0x7f9e10522c18>

max()  #接收序列化类型数据,返回其中值最大的元素

min()  # ..... 返回其中值最小的元素

>>> max(1,2,3)
3
>>> min(1,2,3)
1

memoryview()

          查看内存地址

#memoryview()  
v = memoryview(b'abc123')  
print(v[1])  
print(v[0])  
  
import struct  
buf = struct.pack("i"*12, *list(range(12)))  
x = memoryview(buf)  
y = x.cast('i', shape=[2,2,3])  
print(y.tolist())

输出:

98
97
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]

oct()

    接收一个十进制,转换成八进制

>>> oct(22)
'0o26

ord()

    # 字母转数字,查看ASCII码表

>>> ord('A')
65

pow(x,y)   #求次方,返回x**y的结果

pow(x,y,z)  # 返回 x**y%z 的结果

>>> pow(2,3)
8
>>> pow(3,3,3)
0

property()  # 获取对象的所有属性

>>> property(a)
<property object at 0x7f9e1051da48>
>>> property(1)
<property object at 0x7f9e1051da98>

range()  #返回一系列连续增加的整数

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
>>> range(1,10,2)
[1, 3, 5, 7, 9]

reversed() #返回一个反向迭代器

1、函数功能是反转一个序列对象,将其元素从后向前颠倒构建成一个新的迭代器。

>>> a = reversed(range(10)) # 传入range对象
>>> a # 类型变成迭代器
<在0x035634E8 range_iterator对象>
>>> 名单(一)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>>一个= [ ' 一个',' b ',' c ^ ',' ð ' ]
 >>> 一个
['a', 'b', 'c', 'd']
>>> reversed(a) # 传入列表对象
<在0x031874D0 list_reverseiterator对象>
>>> b = reversed(a)
>>> b # 类型变成迭代器
<在0x037C4EB0 list_reverseiterator对象>
>>> 列表(b)中
[ ' ð ',' Ç ',' b ',' 一个' ]

2、如果参数不是一个序列对象,则其必须定义一个__reversed__方法。

#类型学生没有定义__reversed__方法 
>>> 类学生:
     高清 __init__(个体经营,名称,* 参数):
        self.name = 名称
        self.scores = []
         为值在ARGS:
            self.scores.append(值)

            
>>> A =学生(' 鲍勃',78,85,93,96 )
 >>>逆转(一)#实例不能反转
回溯(最近通话最后一个):
  文件“ <pyshell#37> ” ,第1行,在 <模块>
    逆转(一)
类型错误:参数逆转()必须是一个序列
>>>类型(a.scores) #列表类型 
< 类 ' 列表' >


# 重新定义类型,并为其定义__reversed__方法
>>> class Student:
    def __init__(self,name,*args):
        self.name = 名称
        self.scores = []
         为值在ARGS:
            self.scores.append(值)
    高清 __reversed__ (个体经营):
        self.scores = 反转(self.scores)

        
>>>一个=学生(' 鲍勃',78,85,93,96 )
 >>> a.scores #列表类型 
[78,85,93,96 ]
 >>> 类型(a.scores)
 < 类 ' 列表“ >

>>> reversed(a)  # 实例变得可以反转
>>> a.scores # 反转后类型变成迭代器
<在0x0342F3B0 list_reverseiterator对象>
>>> 类型(a.scores)
 < 类 ' list_reverseiterator ' >

>>> 列表(a.scores)
[96, 93, 85, 78]

round(number[, ndigits]) 

返回浮点值数四舍五入到ndigits小数点后的数字。如果ndigits被省略,它返回到其输入最接近的整数。各位代表number.__round__(ndigits)。

对于内置类型支撑round(),值被四舍五入为10到功率减去最接近多个ndigits ; 如果两个倍数同样接近,舍入朝向甚至选择完成(因此,例如,这两个round(0.5)和round(-0.5)是0,和round(1.5)是2)。返回值是如果用一个参数调用的整数,否则相同的类型的数目。

1、 round函数用于对浮点数进行四舍五入求值,具体保留几位小数,以传入的ndigits参数来控制。

>>> round(1.1314926,1)
1.1
>>> round(1.1314926,5)
1.13149

2、ndigits参数为可选参数,当不传入时,即以默认保留0位小数进行取整,返回的是整数。

>>> round(1.1314926)
1

3、 ndigits参数传入0时,虽然与不传入ndigits参数一样保留0位小数进行四舍五入,但是返回的值是浮点型。

>>> round(1.1314926,0)
1.0

4、ndigits参数小于0时,对整数部分进行四舍五入,ndigits参数控制了对浮点数的整数部分的后几位进行四舍五入,小数部分全部清0,返回类型是浮点数。如果传入的浮点数的整数部分位数小于ndigits参数绝对值,则返回0.0.

>>> round(11314.926,-1)
11310.0
>>> round(11314.926,-3)
11000.0
>>> round(11314.926,-4)
10000.0
>>> round(11314.926,-5)
0.0

5、round四舍五入时是遵循靠近0原则,所以-0.5和0.5进行0位四舍五入,返回的都是0.

>>> round(0.5)
0
>>> round(-0.5)
0

6、对于浮点数求四舍五入有一个陷阱,有些四舍五入结果不像预期那样,比如round(2.675, 2) 的结果是2.67 而不是预期的 2.68,这不是bug,而是浮点数在存储的时候因为位数有限,实际存储的值和显示的值有一定误差。

>>> round(2.675, 2)
2.67

7、对整数也能进行round操作,返回值也是整形。

>>> round(134567)
134567
>>> round(134567,0)
134567
>>> round(134567,1)
134567
>>> round(134567,2)
134567
>>> round(134567,-2)
134600
>>> round(134567,-6)
0

set([iterable])  本函数是从迭代对象生成集合;集合可以增加或删除元素。

>>> tset = set([1, 2, 3, 3, 4, 5, 6, 6])   
>>> print(tset)  
set([1, 2, 3, 4, 5, 6])
>>>   
... tset.add(20)  
>>> print(tset)  
set([1, 2, 3, 4, 5, 6, 20])

setattr(object, name, value)  实现增加或设置对象object一个属性名称name,并设置相应的值value。一般情况与getattr()配套使用。

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> hasattr(t, "age")   #判断属性是否存在
False
>>> setattr(t, "age", "18")   #为属相赋值,并没有返回值
>>> hasattr(t, "age")    #属性存在了
True
>>>

slice

class slice(stop)

class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

说明:

1. 函数实际上是一个切片类的构造函数,返回一个切片对象。

2.切片对象由3个属性start、stop、step组成,start和step默认值为None。切片对象主要用于对序列对象进行切片取对应元素。

>>> help(slice)
Help on class slice in module __builtin__:

class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  indices(...)
 |      S.indices(len) -> (start, stop, stride)
 |      
 |      Assuming a sequence of length len, calculate the start and stop
 |      indices, and the stride length of the extended slice described by
 |      S. Out of bounds indices are clipped in a manner consistent with the
 |      handling of normal slices.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> a[None:5:None] # start step显式为None
[0, 1, 2, 3, 4]
>>> a[:5:] # start step默认为None
[0, 1, 2, 3, 4]
>>> a[2:5:None] # step显式为None
[2, 3, 4]
>>> a[2:5:] # step默认为None
[2, 3, 4]
>>> a[1:10:3]
[1, 4, 7]

staticmethod(function)

Return a static method for function.

A static method does not receive an implicit first argument.

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

说明:

1、类中普通的方法,实际上既可以被类直接调用也可以被类的实例对象调用,但是被实例对象调用的时候,要求方法至少有一个参数,而且调用时会将实例对象本身传给第一个参数。

>>> class Student(object):
    def __init__(self,name):
        self.name = name
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')
  
    
>>> Student.sayHello
<function Student.sayHello at 0x02AC7810>
>>> a = Student('Bob')
>>> a.sayHello
<bound method Student.sayHello of <__main__.Student object at 0x02AD03F0>>


>>> Student.sayHello('en') # 类调用的时候,将'en'传给了lang参数
en
Welcome!

>>> a.sayHello() # 类实例对象调用的时候,将对象本身自动传给了lang参数,不能再接收参数
<__main__.Student object at 0x02AD03F0>
你好!


  >>> a.sayHello('en')
  Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
  a.sayHello('en')
  TypeError: sayHello() takes 1 positional argument but 2 were given

2. staticmethod函数功能就是将一个方法定义成类的静态方法,正确的方法是使用 @staticmethod装饰器,这样在实例对象调用的时候,不会把实例对象本身传入静态方法的第一个参数了。

# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')

            
>>> Student.sayHello('en') #类调用,'en'传给了lang参数
en
Welcome!

>>> b = Student('Kim') #类实例对象调用,不再将类实例对象传入静态方法
>>> b.sayHello()
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    b.sayHello()
TypeError: sayHello() missing 1 required positional argument: 'lang'

>>> b.sayHello('zh')  #类实例对象调用,'zh'传给了lang参数
zh
你好!

sum(iterable[, start])

用来计算可迭代对象iterable的和,然后以这个结果再加上start的值。参数start用来指定相加的参数,如果没有设置这个值,默认是0值。要计算和的序列一般是数字类型,并且开始参数要设置为数字类型。其它有些情况之下,使用别的计算和的方式会更好,比如计算字符串的和使用’’.join(sequence);或者计算浮点数的和使用math.fsum();或者计算多序列的和使用itertools.chain()

>>> l=range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(l,'=',sum(l))
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '=', 45)
>>> print(sum([2, 5, 8], 1))  
16
>>> print(sum([2, 5, 8], 2))  
17
>>> print(sum((2, 3, 4), 1))  
10
>>> print(sum(set([2, 3, 4]), 1))
10

zip([iterable, ...])

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip()is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups usingzip(*[iter(s)]*n).

zip() in conjunction with the * operator can be used to unzip a list:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True


神回复

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。