笔记-python-lib-内置函数

笔记-python-lib-内置函数

注:文档来源为Python3.6.4官方文档

1.      built-in functions

  1. abs(x) 返回绝对值
  2. all(iterable)   return true if all elements of the iterable are true.
  3. any(iterable) return True If any element of the iterable is true.
  4. ascii(object)  类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。 生成字符串类似 Python2 版本中 repr() 函数的返回值。
  5. bin(x)      convert an integer number to a binary string prefied with”0b”
  6. class bool([x])       return a boolena value,True or False.
  7. class bytearray()  return a new array of bytes.

如果 source 为整数,则返回一个长度为 source 的初始化数组;

如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;

如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;

如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。

如果没有输入任何参数,默认就是初始化数组为0个元素。

example:

>>>bytearray()

bytearray(b'')

>>> bytearray([1,2,3])

bytearray(b'\x01\x02\x03')

>>> bytearray('runoob', 'utf-8')

bytearray(b'runoob')

  1. class bytes()
  2. callable(object) return “True” if the object argument appears callable.False if not.
  3. chr(i) return the string representing a character whose Unicode code point in the integer i.

chr(97) >>>a

  1. @classmethod

transform a method into a class method.

classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

class A(object):

    bar = 1

    def func1(self): 

        print ('foo')

    @classmethod

    def func2(cls):

        print ('func2')

        print (cls.bar)

        cls().func1()   # 调用 foo 方法

A.func2()               # 不需要实例化

  1. compile()

compile the source into a code or AST object.

  1. class complex([real[, imag]])

return a complex number with the value real + imag*1j or convert a string o number to a complex number.

  1. delattr(object, name)

this is a relative of setattr(). the ‘name’ must be the name of one of the object’s attributes.

delattr(x, ‘foobar’) is equivalent to del x.foobar

  1. class dict(**kwarg)
  2. dir(object)

without arguments return the list of names in the current local scope.

with an argument, attempt to return a list of valid attributes for that object.

If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

  1. divmod(a, b)

for intergers, the result is the same as(a//b, a%b).

for floating point numbers the result is (q, a%b)

>>> divmod(200.3345, 4)

(50.0, 0.33449999999999136)

  1. enumerate(iterable, start=0)

return an enumerate object.

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

for i, element in enumerate(seq):

print(i, seq[i])

  1. eval(expression, globals= None, locals=None)

eval() 函数用来执行一个字符串表达式,并返回表达式的值

expression -- 表达式。

globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。

locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

  1. exec(object[, globals[, locals]])

exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。

  1. filter(function, iterable)

construct an iterator from those elements of iterable for which function returns true.iterable may be either a sequence, a container which supports iteration, or an iterator.

  1. class float([x])
  2. format(value[, format_spec])
  3. class frozenset([iterable])

return a new frozenset object, optionally with elements taken from iterable.

frozenset object is a built-in class.

  1. getattr(object, name[, default])

return the value of the named attribute of object.

  1. globals()

return a dictionary representing the current global symbol table.

  1. hasattr(object, name)

the arguments are an object and a string.The result is True if the string is the name of the object’s attributes, False if not.

  1. hash(object)

return the hash value of the object(if it has one).Hash value are

hash() 函数可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。

在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。

class Test:

    def __init__(self, i):

        self.i = i

for i in range(50):

    t = Test(1)

print(hash(t), id(t))

       测试后发现确实会在两个值之间切换.

  1. help([object])
  2. hex(x)

convert an interger number to a lowercase hexadecimal string prefixed with ‘0x’

  1. id(object)

return the “identity” of an object. this is an integer which is guaranteed to be unique and constant for this object during its lifetime.

  1. input([prompt])
  2. class int(x=0)

class int(x, base=10)

  1. isinstance(object, classinfo)

return true if the object argument is an instance of the classinfo argument.

  1. issubclass(class, classinfo)
  2. iter(object[, sentinel])

return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument.

sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。

  1. len()
  2. class list([iterable])
  3. locals()
  4. map(function, iterable, …)

Return an iterator that applies function to every item of iterable, yielding the results.

def f(x):

    return x**2

lista = [x for x in range(18)]

listb = list(map(f, lista))

print(listb)

注意:在python3中返回的是iterator,需手动转换。

  1. max()
  2. memoryview(obj)
  3. min()
  4. next()
  5. oct(x)
  6. open()
  7. ord(c)
  8. pow(x, y[, z])
  9. print()
  10. class property(fget=None, fset=None, fdel=None, doc=None)
  11. range()
  12. repr(object)

return a string containg a printable representation

  1. reversed(seq)
  2. round(number[, ndigits])
  3. class set([iterable])
  4. setattr(object, name, value)
  5. class slice()
  6. sorted(iterable, *, key=None, reverse=False)
  7. @staticmethod
  8. sum(iterable[, start])
  9. super([type[, object-or-type]])
  10. tupple([iterable])
  11. class type(object)
  12. vars([object])
  13. zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

zip支持解包操作。

>>> x = [1, 2, 3]

>>> y = [4, 5, 6]

>>> zipped = zip(x, y)

>>> list(zipped)

[(1, 4), (2, 5), (3, 6)]

>>> x2, y2 = zip(*zip(x, y))

>>> x == list(x2) and y == list(y2)

True

  1. __import__(name, globals=None, locals=None, fromlist=(), level=0)

猜你喜欢

转载自www.cnblogs.com/wodeboke-y/p/9696609.html