Python基础_内置函数

 

  Built-in Functions  
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
# abs(x)
print(abs(-10))  # 10
# 取绝对值

###################################
# all(iterable)
print(all([1,2,3,4,5]))  # True
print(all((0,1,2,3,4)))  # False
# 可迭代对象中,如果存在一个以上bool为False的,则整体为False

###################################
# any(iterable)
print(any([None,False,(),[],{},]))  # False
print(any([None,False,(),[],{},10]))  # True
# 可迭代对象中,只要存在一个是True,则为True

###################################
# ascii(object)
print(ascii("abcd"))  # 'abcd'
print(ascii("中国"))  # '\u4e2d\u56fd'

###################################
# bin(x)
print(bin(3))  # 0b11
print(bin(-10))  # -0b1010
# 二进制

###################################
# bool([x])
print(bool(None))  # False
print(bool(2))  # True

###################################
# breakpoint(*args, **kws)
# print(breakpoint())  # 3.6

###################################
# bytearray([source[, encoding[, errors]]])
print(bytearray())  # bytearray(b'')
print(bytearray([1,2,3]))  # bytearray(b'\x01\x02\x03')
print(bytearray('test', 'utf-8'))  # bytearray(b'test')
# 如果 source 为整数,则返回一个长度为 source 的初始化数组;
# 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
# 如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
# 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
# 如果没有输入任何参数,默认就是初始化数组为0个元素。
# bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

###################################
# bytes([source[, encoding[, errors]]])
print(bytes("中国","utf-8"))  # b'\xe4\xb8\xad\xe5\x9b\xbd'
print(bytes("中国","gbk"))  # b'\xd6\xd0\xb9\xfa'
print(bytes("hello world","utf-8"))  # b'hello world'
print(bytes("hello world","gbk"))  # b'hello world'

###################################
# callable(object)
def test():
    pass

class T():
    pass
class T1():
    def __call__(self):
        pass

print(callable([1,2,3]))  # False
print(callable(test))  # True
print(callable(T()))  # False
print(callable(T1()))  # True
# 验证对象是否实现了__call__方法

###################################
# chr(i)
print(chr(77))  # M
# 通过ascii码得出对应的字符
print(ord("M"))  # 77
# 反向,查找出字符对应的ascii码

###################################
# classmethod
# 类方法

###################################
# compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
str = "for i in range(0,10): print(i)"
c = compile(str,'','exec')   # 编译为字节代码对象
exec(c)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# compile() 函数将一个字符串编译为字节代码。

###################################
# complex([real[, imag]])
print(complex(1, 2))  # (1+2j)
# complex() 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

###################################
# delattr(object, name)
# 反射

###################################
# dir([object])
# 查看对象的namespace

###################################
# divmod(a, b)
print(divmod(100,3))  # (33, 1)
# a被除数,b除数
# res:(商,余数)

###################################
# enumerate(iterable, start=0)
for index,value in enumerate([123,32,2],start=3):
    print(index,value)
# 3 123
# 4 32
# 5 2

###################################
# eval(expression, globals=None, locals=None)
print(eval("1+2+3*4"))  # 15
print(eval("x+y",{"x":1,"y":2}))  # 3
# 计算指定表达式的值

###################################
# exec(object[, globals[, locals]])
class T():
    pass
exec("x = T()")
print(x)  # <__main__.T object at 0x05A81050>

x = 10
expr = """
z = 30
sum = x + y + z   #一大包代码
print(sum)
"""
def func():
    y = 20
    exec(expr)  # 10+20+30
    exec(expr,{'x':1,'y':2})  # 30+1+2
    exec(expr,{'x':1,'y':2},{'y':3,'z':4})  # 30+1+3,x是定义全局变量1,y是局部变量
func()
# 60
# 33
# 34

# 动态执行python代码,exec无返回值

###################################
# filter(function,iterable)
print(list(filter(lambda x:x>4,[1,2,3,4,5,6,7,8,9])))  # [5, 6, 7, 8, 9]
# filter对象是一个迭代器,筛选

###################################
# float([x])
print(float(-123))  # -123.0
print(float('1e-003'))  # 0.001
print(float('+1E6'))  # 1000000.0
print(float("-Infinity"))  # -inf

###################################
# format(value[, format_spec])
print(format(3,'b')) #转换成二进制  '11'
print(format(314159267,'0.2E')) #科学计数法,指定保留2位小数,采用大写E表示 '3.14E+08'

###################################
# frozenset([iterable])
print(frozenset([1,2,3,4]))  # frozenset({1, 2, 3, 4})
# 不能改变,没有add,remove

###################################
# getattr(object, name[, default])
# 反射

###################################
# globals()
print(globals())
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x03B6B450>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/Python相关/过程project/爬虫复习/第一次review/tmp.py', '__cached__': None, 'test': <function test at 0x057F07C8>, 'T': <class '__main__.T'>, 'T1': <class '__main__.T1'>, 'index': 5, 'value': 2, 'x': 10, 'expr': '\nz = 30\nsum = x + y + z   #一大包代码\nprint(sum)\n', 'func': <function func at 0x057F0780>}
# 全局变量

###################################
# hasattr(object, name)
# 反射

###################################
# hash(object)
print(hash('good good study'))  # -724571439
print(hash(1.0))  # 1
print(hash(1))  # 1
print(hash(1.0000))  # 1
# hash() 用于获取取一个对象(字符串或者数值等)的哈希值。

###################################
# help([object])
help('str')
# help() 函数用于查看函数或模块用途的详细说明。

###################################
# hex(x)
print(hex(255))  # 0xff
print(hex(12))  # 0xc
print(type(hex(123)))  # <class 'str'>
# hex() 函数用于将10进制整数转换成16进制,以字符串形式表示。

###################################
# id([object])
# id() 函数用于获取对象的内存地址。

###################################
# input([prompt])
# input("input:")  # input:
# input() 函数接受一个标准输入数据,返回为 string 类型。

###################################
# class int(x, base=10)
print(int(3.2))  # 3
print(int('12',16))  # 18
print(int("16",8))  # 14
# int() 函数用于将一个字符串或数字转换为整型。

###################################
# isinstance(object, classinfo)
# isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。

###################################
# issubclass(class, classinfo)
# issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。

###################################
# iter(object[, sentinel])
l = iter([1,2,3])
print(next(l))  # 1
print(next(l))  # 2
# iter() 函数用来生成迭代器。

###################################
# len( s )
# Python len() 方法返回对象(字符、列表、元组等)长度或项目个数。

###################################
# list( seq )
# list() 方法用于将元组转换为列表。

###################################
# locals()
# locals() 函数会以字典类型返回当前位置的全部局部变量。

###################################
# map(function, iterable, ...)
print(list(map(lambda x:x**3,[1,2,3])))  # [1, 8, 27]
# map() 会根据提供的函数对指定序列做映射。

###################################
# max(iterable, *[, key, default])
# max(arg1, arg2, *args[, key])
d = {"a":10,"b":9,"c":8,"d":7,"e":6}
print(max(d))  # e
print(max(d,key=lambda x:d[x]))  # a

###################################
# memoryview(obj)
v = memoryview(bytearray("abcefg", 'utf-8'))
print(v[1])  # 98
print(v[-1])  # 103
print(v[1:4])  # <memory at 0x09F7D8B8>
print(v[1:4].tobytes())  # b'bce'
# memoryview() 函数返回给定参数的内存查看对象(Momory view)。
# 所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。

###################################
# min(iterable, *[, key, default])
# min(arg1, arg2, *args[, key])
d = {"a":10,"b":9,"c":8,"d":7,"e":6}
print(min(d))  # a
print(min(d,key=lambda x:d[x]))  # e

###################################
# next(iterator[, default])
# next() 返回迭代器的下一个项目。

###################################
# oct(x)
print(oct(10))  # 0o12
print(oct(20))  # 0o24
# oct() 函数将一个整数转换成8进制字符串。

###################################
# open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

###################################
# ord(c)
# ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

###################################
# pow(x, y[, z])
print(pow(2,10))  # 1024
print(pow(2,10,10))  # 4,取模,等价于pow(x,y) %z
# 返回 xy(x的y次方) 的值。

###################################
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

###################################
# property(fget=None, fset=None, fdel=None, doc=None)

###################################
# range(stop)
# range(start, stop[, step])

###################################
# repr(object)
# repr() 函数将对象转化为供解释器读取的形式。

###################################
# reversed(seq)
seqRange = range(5, 9)
print(list(reversed(seqRange)))  # [8, 7, 6, 5]
# reversed 函数返回一个反转的迭代器。

###################################
# round(number[, ndigits])
print ("round(70.23456) : ", round(70.23456))  # round(70.23456) :  70
print ("round(-100.000056, 3) : ", round(-100.000056, 3))  # round(-100.000056, 3) :  -100.0
# round() 方法返回浮点数x的四舍五入值。

###################################
# set([iterable])

###################################
# setattr(object, name, value)
# 反射

###################################
# slice(stop)
# slice(start, stop[, step])
myslice = slice(5)    # 设置截取5个元素的切片
myslice1 = slice(2,9)
myslice2 = slice(2,9,3)
arr = range(10)
print(arr[myslice])  # range(0, 5)
print(arr[myslice1])  # range(2, 9)
print(arr[myslice2])  # range(2, 9, 3)
# slice() 函数实现切片对象,主要用在切片操作函数里的参数传递。

###################################
# sorted(iterable, *, key=None, reverse=False)
print(sorted([5, 2, 3, 1, 4]))  # [1, 2, 3, 4, 5]
print(sorted([5, 0, 6, 1, 2, 7, 3, 4], key=lambda x: x*-1))  # [7, 6, 5, 4, 3, 2, 1, 0]
# sorted() 函数对所有可迭代的对象进行排序操作。

###################################
# staticmethod

###################################
# str(object='')
# str(object=b'', encoding='utf-8', errors='strict')

###################################
# sum(iterable[, start])
print(sum((2, 3, 4), 1))        # 10 元组计算总和后再加 1
print(sum((range(3,5)), 3))        # 10 元组计算总和后再加 3
# sum() 方法对系列进行求和计算。

###################################
# super([type[, object-or-type]])
# super() 函数是用于调用父类(超类)的一个方法。

###################################
# tuple([iterable])
# tuple 函数将列表转换为元组。。

###################################
# type(object)
# type(name, bases, dict)
print(type(1))  # <class 'int'>
print(type("abc"))  # <class 'str'>
# 三个参数
class X():
    a = 1
z = type("X",(object,),dict(a=1))
print(z)  # <class '__main__.X'>

###################################
# vars([object])
class X(object):
    a = 1
print(vars(X))  # {'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
# vars() 函数返回对象object的属性和属性值的字典对象。

###################################
# zip(*iterables)
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
print(list(zip(a,b,c)))  # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

###################################
# __import__(name, globals=None, locals=None, fromlist=(), level=0)
# __import__() 函数用于动态加载类和函数 。
逐个实现

 

参考or转发

 http://www.runoob.com/python/python-built-in-functions.html
posted @ 2018-08-20 22:17  fat39  阅读(301)  评论(0编辑  收藏  举报