Built-in Functions(68个)

1、数学方法

abs() sum() pow() min() max() divmod() round()

2、进制转换

bin() oct() hex()

3、简单数据类型

- 整数:int()

- 浮点数:float()

- 字符\字符串:str() repr() ascii() ord() chr() format()

- 字节:bytes() bytearray()

- 布尔:bool()

- 复数:complex()

4、数据结构

- 列表:list() slice() range()

- 元组:tuple()

- 字典:dict() hash()

- 集合:set() frozenset()

- 方法:len() zip() all() any() iter() filter() next() sorted() reversed() enumerate() map() memoryview()

5、面向对象

setattr() getattr() delattr() hasattr()

super() property()

staticmethod() classmethod()

isinstance() issubclass()

6、系统方法

dir() help() id() object() type()

input() open() print()

eval() exec() compile()

vars() locals() globals()

callable() ​​__import__()​


参考:​​https://docs.python.org/3.5/library/functions.html​


print(abs(-1))  # 绝对值  1
print(divmod(5, 2)) # 取商和余数 (2, 1)

# 四舍五入
print(round(1.4)) # 1
print(round(1.5)) # 2
print(round(1.6)) # 2

# 次方,相当于x**y
print(pow(2, 8)) # 256

print(bin(2)) # 转为二进制 0b10
print(oct(12)) # 转8进制 0o14
print(hex(20)) # 转16进制 0x14

print(bool(1)) # 转为布尔值 True

# 转为int
s = "12"
i = int(s)
print(type(s), type(i)) # <class 'str'> <class 'int'>

# 转字符串
i = 12345
s =str(i)
print(type(i), type(s)) # <class 'int'> <class 'str'>

print([ascii([1,2,3])]) # 转为字符串 ['[1, 2, 3]']

# 转为可打印对象representation 表现
s = 123456
r =repr(s)
print(type(s), type(r)) # <class 'int'> <class 'str'>

# ascii码
print(chr(100)) # d
print(ord("a")) # 97

print(bytes("我是中国人", encoding="utf-8"))
# b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'

b = bytearray("abc", encoding="utf-8") # 转为字节数组
print(b) # bytearray(b'abc')
print(b[0]) # 97
b[0] = 100
print(b) # bytearray(b'dbc')

# 新建字典对象
d1 = {}
d2 = dict()
d3 = dict(name = "Tom", age = 23)
print(d1) # {}
print(d2) # {}
print(d3) # {'age': 23, 'name': 'Tom'}

# 获取散列值
res = hash(1)
print(res) # 1

res = hash("Tom") # -1433634475463391166
print(res)

# 不可变集合
st = frozenset([1,2,3,4])
print(type(st)) # <class 'frozenset'>

# 生成列表
lst1 = []
lst2 = list()
lst3 = list((1,2,3))
print(lst1) # []
print(lst2) # []
print(lst3) # [1, 2, 3]

# 计算长度
print(len([1,2,3])) # 3

# 最大最小值
lst = [1,3,4,5,8,6,9]
print(max(lst)) # 9
print(min(lst)) # 1

# 求和
lst = [i for i in range(5)]
print(sum(lst)) # 10

# 切片
lst = [x for x in range(10)]
s = slice(2,5)
print(lst[s]) # [2, 3, 4]

# 枚举
for index, value in enumerate(range(1,5)):
print(index, value)
"""
0 1
1 2
2 3
3 4
"""

print(all([1,2,3])) # 所有都是真的 True
print(all([1,2,0])) # False
print(any([1,2,1])) # 至少存在一个真的 True
print(any([0])) # False

# 元组
t1 = ()
t2 = (1,)
t3 = tuple()
print(type(t1)) # <class 'tuple'>
print(type(t2)) # <class 'tuple'>
print(type(t3)) # <class 'tuple'>

# 反转
lst = [1, 2, 3]
print(reversed(lst)) # <list_reverseiterator object at 0x0000000003A54A90>

# lambda 与 三元运算符
lamb = lambda x : 3 if x < 5 else x
print(lamb(5)) # 5

# 过滤
res = filter(lambda x: x>5, range(10))
for i in res:
print(i,end=" ") # 6 7 8 9
print()

# 映射
res = map(lambda x: x*x, range(10))
for i in res:
print(i, end=" ") # 0 1 4 9 16 25 36 49 64 81
print()
"""
等价于:
res = [lambda x: x*x for x in range(10)]
res = [x*x for x in range(10)]
"""

# 浓缩
import functools # py3
res = functools.reduce(lambda x, y: x + y, range(10))
print(res) # 45

# 排序
dct ={"0": 99, "1": 98, "6": 11, "5": 45}
print(dct) # {'6': 11, '0': 99, '1': 98, '5': 45}
print(sorted(dct)) # ['0', '1', '5', '6']
print(sorted(dct.items()))
# [('0', 99), ('1', 98), ('5', 45), ('6', 11)]
print(sorted(dct.items(), key=lambda x: x[1]))
# [('6', 11), ('5', 45), ('1', 98), ('0', 99)]

# 拉链,这个叫法很形象
a = [1, 2, 3, 4, 5]
b = ["a", "b", "c", "d", "e"]
z = zip(a, b)
print(z) # <zip object at 0x0000000003FBE1C8>
print([i for i in z])
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]

# 转为迭代器
lst = [1, 2, 3]
ilst = iter(lst)
print(type(lst),type(ilst)) # <class 'list'> <class 'list_iterator'>

# 相当于生成器的__next()__ 方法
lst = range(5)
print(type(ilst)) # <class 'range'>
ilst = iter(lst)
print(type(ilst)) # <class 'range_iterator'>
print(next(ilst)) # 0
print(next(ilst)) # 1

# 判断是否为某个类的实例
d ={}
print(isinstance(d, dict)) # True

# 导入包 动态加载类和函数
__import__("iterator_test")
print()

print(dir(d1)) # 查看方法
"""
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items',
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
"""

print(help(divmod)) # 查看帮助
"""
Help on built-in function divmod in module builtins:

divmod(...)
divmod(x, y) -> (div, mod)

Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
"""

# 对象id
a = 1
print(id(a)) # 1430299072

# 打印局部变量
def foo():
a = 1
print(vars()) # {'a': 1}
foo()

# 打印局部变量
def foo():
a = 1
print(locals()) # {'a': 1}
foo()

print(globals()) # 打印当前文件的所有全局变量,key-value形式返回
"""
{'code': '\nfor i in range(5):\n print(i, end=" ")\n',
'__cached__': None, 'value': 4, 'index': 3, 'd1': {},
'b': bytearray(b'dbc'), 'lamb': <function <lambda> at 0x00000000024E8730>,
'__package__': None, 'st': frozenset({1, 2, 3, 4}),
...
"""

code = """
for i in range(5):
print(i, end=" ")
"""
exec(code) # 运行代码 0 1 2 3 4
x = 1
print("eval:", eval("x+1")) # eval: 2

def sayHello():pass
print(callable(sayHello)) # True