内置函数

时间:2019-09-27
本文章向大家介绍内置函数,主要包括内置函数使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

内置函数

一、内置函数

更多内置函数:https://docs.python.org/3/library/functions.html?highlight=built#ascii

1.1 掌握

解码字符。

res = '你好'.encode('utf8')
print(res)

b'\xe4\xbd\xa0\xe5\xa5\xbd'

res = bytes('你好', encoding='utf8')
print(res)

b'\xe4\xbd\xa0\xe5\xa5\xbd'

2.chr()/ord()

chr()参考ASCII码表将数字转成对应字符;ord()将字符转换成对应的数字。

print(chr(65))

A

print(ord('A'))

65

3.divmod()

分栏。

print(divmod(10, 3))

(3, 1)

4.enumerate()

带有索引的迭代。

l = ['a', 'b', 'c']
for i in enumerate(l):
    print(i)

(0, 'a')
(1, 'b')
(2, 'c')

5.eval()

把字符串翻译成数据类型。

lis = '[1,2,3]'
lis_eval = eval(lis)
print(lis_eval)

[1, 2, 3]

6.hash()

是否可哈希。

print(hash(1))

1

1.2 了解

求绝对值。

print(abs(-13))  # 求绝对值

13

2.all()

可迭代对象内元素全为真,则返回真。

print(all([1, 2, 3, 0]))
print(all([]))

False
True

3.any()

可迭代对象中有一元素为真,则为真。

print(any([1, 2, 3, 0]))
print(any([]))

True
False

4.bin()/oct()/hex()

二进制、八进制、十六进制转换。

print(bin(17))
print(oct(17))
print(hex(17))

0b10001
0o21
0x11

5.dir()

列举出所有time的功能。

import time
print(dir(time))

['_STRUCT_TM_ITEMS', 'doc', 'loader', 'name', 'package', 'spec', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']

6.frozenset()

不可变集合。

s = frozenset({1, 2, 3})
print(s)

frozenset({1, 2, 3})

7.globals()/loacals()

查看全局名字;查看局部名字。

# print(globals())
def func():
    a = 1
#     print(globals())
    print(locals())


func()

{'a': 1}

8.pow()

print(pow(3, 2, 3))  # (3**2)%3

0

9.round()

print(round(3.5))

4

10.slice()

lis = ['a', 'b', 'c']
s = slice(1, 4, 1)
print(lis[s])  # print(lis[1:4:1])

['b', 'c']

11.sum()

print(sum(range(100)))

4950

12.__import__()

通过字符串导入模块。

m = __import__('time')
print(m.time())

1565782380.0657628

1.3 面向对象知识点

  1. classmethod
  2. staticmethod
  3. property
  4. delattr
  5. hasattr
  6. getattr
  7. setattr
  8. isinstance()
  9. issubclass()
  10. object()
  11. super()

原文地址:https://www.cnblogs.com/Lin2396/p/11596359.html