跟我一起学python-内置函数

luckyFang 2021年10月07日 37次浏览

跟我一起学pyton-内置函数

内置函数

特点: 无需导入,直接使用

python提供了68个内置函数,分别是

  • 数字运算函数(7个)
    • abs(x) 绝对值
    • divmod(x,y) 返回商和余数
    • pow(x,y[,z]) 返回 x**y
    • round(x,[,n]) 四舍五入
    • max(x1,x2,...xn) 最大值
    • min(x1,x2,...xn) 最小值
    • sum(iterable) 求和
  • 序列运算函数(8个)
    • all(iterable) 判断可迭代对象每个元素值是否是True
    • any(iterable) 判断可迭代对象中值是否有True
    • filter(function,iterable)过滤器:通过第一个参数的函数来决策
    • map(function,iterable) 对每个可迭代对象依次执行function
    • next(iterator,[default])返回迭代器中下一个元素,如果不存在则采用可选参数默认值
    • reversed(seq)翻转序列
    • sorted(iterable,[,key=None][,reverse=False])对可迭代对象进行排序
    • zip([iterable...])将可迭代对象打包为一个元组
  • 对象运算函数(16个)
    • help([object])返回对象帮助信息
    • dir([object])查看一个对象的属性方法列表,不带参数时返回当前范围内的变量,方法和定义的类型列表
    • id([object])查看对象唯一标识符(内存地址)
    • hash(object)查看对象的哈希值
    • type(object)查看对象类型
    • len(object)返回对象长度
    • ascii(object)将非ascii转换为 ascii
    • format(object)格式化字符串
    • isinstance(object,classinfo)查看一个对象是否是已知类型
    • issubclass(class,classinfo)查看一个对象是否是classinfo的子类
    • hasattr(object,name)判断一个对象是否有指定的属性
    • getattr(object,name,[,default])获取一个对象的属性
    • setattr(object,name,value)设置一个对象的属性
    • delattr(object,name)删除一个对象的属性
    • callable(object)检测对象是否可调用
    • vars([object])返回对象的object的属性和属性值字典对象
  • 类型转换函数(24个)
    • bool([x])转换为布尔值
    • int(x)转换为整数
    • float(x)转换为浮点型
    • complex(x[,y])复数,实部:x,虚部:y
    • str(object)转换为字符串
    • bytearry([source[,encoding[,errors]]])转换为可变字节数组
    • bytes([source[,encoding[,errors]]])转换为不可变字节数组
    • memoryview(obj)内存查看对象
    • ord(ch)ascii值
    • chr(x)ascii转换字符
    • bin(x)二进制
    • oct(x)八进制
    • hex(x)十六进制
    • tuple([iterable])可迭代对象转换为元组
    • list([iterable])可迭代对象转换为列表
    • dict(**kwargs)转换为字典
    • set([iterable])转换为可变集合
    • frozenset([iterable])转换为不可变集合
    • enumerate(sequence,[start=0])创建一个枚举对象
    • range(stop)/range(start,stop[,step])创建一个可迭代对象
    • iter(object[,sentinel])创建一个迭代器
    • slice(stop)创建一个切片对象
    • super(type[,object-or-type])方法调用委托父类
    • object()返回一个object对象
  • 其他内置函数(13个)
    • input([prompt])标准输入
    • print(*objects,sep="",end="",file=sys.stdout)标准输出
    • globals()返回当前位置的全局变量
    • locals()返回当前位置的局部变量
    • __import__()动态导入模块
    • open(file,mode="r")打开文件
    • compile()字符串编译为字节代码
    • eval()执行字符串表达式
    • exec()动态执行python语句
    • repr(object)对象转化为供解释器读取的string类型
    • property()返回类属性值
    • classmethod()返回函数的类方法
    • staticmethod(function)返回函数的静态方法

数字运算函数

def printl(st):
    print("=" * 3, st, "=" * 3)


printl("abs")
print(abs(-10))

printl("divmod")
a, b = divmod(22, 7)
print(a, b)

printl("pow")
print(pow(2, 3))

printl("round")
print(round(3.14159, 2))

printl("max")
print(max(10, 2, 3))
print(max([1, 2, 3, 4, 5, ]))

printl("min")
print(min(0, -2, 3))
lst = [-1, -2, -3, 5]
print(min(lst))

printl("sum")
print(sum(lst))
=== abs ===
10
=== divmod ===
3 1
=== pow ===
8
=== round ===
3.14
=== max ===
10
5
=== min ===
-2
-3
=== sum ===
-1

序列运算函数

## 序列运算函数

printl("all")
lst = [1, 1, 1]
print(all(lst))
lst = [1, 0, 1]
print(all(lst))

printl("any")
lst = [1, 0, 0]
print(any(lst))
lst = [0, 0, 0]
print(any(lst))

printl("filter")
lst = range(10)
print(*lst)
print(*(filter(lambda x: x % 2 == 0, lst)))

printl("map")
lst = range(10)
print(*lst)
print(*map(lambda x: x ** 2, lst))

printl("next")
lst = iter(range(4))
print(next(lst))
print(next(lst))

printl("reversed")
lst = range(5)
print(*lst)
print(*reversed(lst))

printl("sorted")
lst = [2, 3, -1, 6, 8, 22, 9, 15]
print(lst)
print(sorted(lst))
print(sorted(lst, reverse=True))

printl("zip")
l1 = ["tom", "jack", "alice", "eric"]
l2 = [20, 18, 19, 22, 20]
zipped = zip(l1, l2)
print(zipped)

printl("unzip")
a, b = zip(*zipped)
print(a)
print(b)
=== all ===
True
False
=== any ===
True
False
=== filter ===
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8
=== map ===
0 1 2 3 4 5 6 7 8 9
0 1 4 9 16 25 36 49 64 81
=== next ===
0
1
=== reversed ===
0 1 2 3 4
4 3 2 1 0
=== sorted ===
[2, 3, -1, 6, 8, 22, 9, 15]
[-1, 2, 3, 6, 8, 9, 15, 22]
[22, 15, 9, 8, 6, 3, 2, -1]
=== zip ===
<zip object at 0x1102a0140>
=== unzip ===
('tom', 'jack', 'alice', 'eric')
(20, 18, 19, 22)

对象运算函数

# 对象运算内置函数
printl("help")
print(help(print))
print(help(input))

printl("dir")
import os

print(dir())
print(dir(os))

printl("id")
a = 10
print(id(a))

printl("type")
print(type("a"))
print(type(1))

printl("len")
print(len([1, 2, 3, 4, 5]))

printl("ascii")
print(ascii("你好"))

printl("format")
str = "我叫{},我今年{}岁了".format("fang", 22)
print(str)

printl("isinstance")
print(isinstance("a", int))
print(isinstance([], list))

printl("issubclass")


class Animal:
    pass


class Dog(Animal):
    pass


print(issubclass(Dog, Animal))

printl("hasattr")
print(hasattr(Animal, "bark"))

printl("setattr")
setattr(Animal, "name", "petter")

printl("getattr")
print(getattr(Animal, "name"))

printl("delattr")
print(hasattr(Animal, "name"))
delattr(Animal, "name")
print(hasattr(Animal, "name"))

printl("callable")
print(callable(Animal))
print(Animal())
print(vars(Animal))
setattr(Animal, "name", "petter")

printl("vars")
print(vars(Animal))

=== help ===
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

None
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

None
=== dir ===
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'l1', 'l2', 'lst', 'os', 'printl', 'random', 'zipped']
['CLD_CONTINUED', 'CLD_DUMPED', 'CLD_EXITED', 'CLD_KILLED', 'CLD_STOPPED', 'CLD_TRAPPED', 'DirEntry', 'EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_LOCK', 'F_OK', 'F_TEST', 'F_TLOCK', 'F_ULOCK', 'GenericAlias', 'Mapping', 'MutableMapping', 'NGROUPS_MAX', 'O_ACCMODE', 'O_APPEND', 'O_ASYNC', 'O_CLOEXEC', 'O_CREAT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_EXLOCK', 'O_NDELAY', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_SHLOCK', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'POSIX_SPAWN_CLOSE', 'POSIX_SPAWN_DUP2', 'POSIX_SPAWN_OPEN', 'PRIO_PGRP', 'PRIO_PROCESS', 'PRIO_USER', 'P_ALL', 'P_NOWAIT', 'P_NOWAITO', 'P_PGID', 'P_PID', 'P_WAIT', 'PathLike', 'RTLD_GLOBAL', 'RTLD_LAZY', 'RTLD_LOCAL', 'RTLD_NODELETE', 'RTLD_NOLOAD', 'RTLD_NOW', 'R_OK', 'SCHED_FIFO', 'SCHED_OTHER', 'SCHED_RR', 'SEEK_CUR', 'SEEK_DATA', 'SEEK_END', 'SEEK_HOLE', 'SEEK_SET', 'ST_NOSUID', 'ST_RDONLY', 'TMP_MAX', 'WCONTINUED', 'WCOREDUMP', 'WEXITED', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WNOWAIT', 'WSTOPPED', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_check_methods', '_execvpe', '_exists', '_exit', '_fspath', '_fwalk', '_get_exports_list', '_spawnvef', '_walk', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chflags', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'cpu_count', 'ctermid', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'environb', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'fwalk', 'get_blocking', 'get_exec_path', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getegid', 'getenv', 'getenvb', 'geteuid', 'getgid', 'getgrouplist', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getpriority', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchflags', 'lchmod', 'lchown', 'linesep', 'link', 'listdir', 'lockf', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 'posix_spawn', 'posix_spawnp', 'pread', 'preadv', 'putenv', 'pwrite', 'pwritev', 'read', 'readlink', 'readv', 'register_at_fork', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sched_get_priority_max', 'sched_get_priority_min', 'sched_yield', 'sendfile', 'sep', 'set_blocking', 'set_inheritable', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setpriority', 'setregid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'st', 'stat', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sync', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'terminal_size', 'times', 'times_result', 'truncate', 'ttyname', 'umask', 'uname', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'waitstatus_to_exitcode', 'walk', 'write', 'writev']
=== id ===
4330396240
=== type ===
<class 'str'>
<class 'int'>
=== len ===
5
=== ascii ===
'\u4f60\u597d'
=== format ===
我叫fang,我今年22岁了
=== isinstance ===
False
True
=== issubclass ===
True
=== hasattr ===
False
=== setattr ===
=== getattr ===
petter
=== delattr ===
True
False
=== callable ===
True
<__main__.Animal object at 0x114286b50>
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Animal' objects>, '__weakref__': <attribute '__weakref__' of 'Animal' objects>, '__doc__': None}
=== vars ===
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Animal' objects>, '__weakref__': <attribute '__weakref__' of 'Animal' objects>, '__doc__': None, 'name': 'petter'}

类型转换函数


print("=" * 100)

printl("bool")
print(bool(1))
print(bool(0))

printl("int")
print(int(10.2))

printl("float")
print(float(10))

printl("complex")
print(complex(2, 3))

printl("str")
print(str(2))

printl("bytearry")
print(bytearray([1, 2, 3]))

printl("bytes")
print(bytes([1, 2, 3]))

printl("memoryview")

view = memoryview(bytearray("abc", "utf8"))
print(view[0])
print(view[1])

printl("ord")
print(ord('A'))

printl("chr")
print(chr(97))

printl("bin")
print(bin(10))

printl("oct")
print(oct(22))

printl("hex")
print(hex(1024))

printl("tuple")
print(tuple([1, 2, 3, 4, 5]))

printl("list")
print(list((1, 2, 3)))

printl("dict")
print(dict(name="jack", age=22))

printl("set")
print(set(range(10)))

printl("frozenset")
print(frozenset(range(10)))

printl("enumerate")
for item in enumerate(["jack", "tom", "eric", "jerry"]):
    print(item)

printl("range")
for item in range(1, 11, 2):
    print(item)

printl("iter")
for item in iter((1, 2, 3, 45)):
    print(item)


printl("slice")
sl = slice(3)
lst = range(10)
print(*lst[sl])

printl("super")
print(super.__dir__(Animal))

printl("object")
ob = object()
print(ob)
=== bool ===
True
False
=== int ===
10
=== float ===
10.0
=== complex ===
(2+3j)
=== str ===
2
=== bytearry ===
bytearray(b'\x01\x02\x03')
=== bytes ===
b'\x01\x02\x03'
=== memoryview ===
97
98
=== ord ===
65
=== chr ===
a
=== bin ===
0b1010
=== oct ===
0o26
=== hex ===
0x400
=== tuple ===
(1, 2, 3, 4, 5)
=== list ===
[1, 2, 3]
=== dict ===
{'name': 'jack', 'age': 22}
=== set ===
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
=== frozenset ===
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
=== enumerate ===
(0, 'jack')
(1, 'tom')
(2, 'eric')
(3, 'jerry')
=== range ===
1
3
5
7
9
=== iter ===
1
2
3
45
=== slice ===
0 1 2
=== super ===
['__repr__', '__call__', '__getattribute__', '__setattr__', '__delattr__', '__init__', '__new__', 'mro', '__subclasses__', '__prepare__', '__instancecheck__', '__subclasscheck__', '__dir__', '__sizeof__', '__basicsize__', '__itemsize__', '__flags__', '__weakrefoffset__', '__base__', '__dictoffset__', '__mro__', '__name__', '__qualname__', '__bases__', '__module__', '__abstractmethods__', '__dict__', '__doc__', '__text_signature__', '__hash__', '__str__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__class__']
=== object ===
<object object at 0x1162ddfe0>

其他内置函数

# 其他内置函数

printl("input")
print(input("hi"))

printl("print")
print("a", "b", "c", sep=' ', end='$\n')

printl("globals")
print(globals())

printl("locals")
print(locals())

printl("__import__")
__import__("math")
print(math.sqrt(20))

printl("open")
with open("base_inner.py") as f:
    pass

printl("compile")
print(compile("print(10)", '', "exec"))

printl("eval")
print(eval("1+2*3"))

printl("exec")
exec("a = 1+2*3;print('a=',a)")

printl("repr")
print(repr(Animal))

printl("property")
print(property())

printl("classmethod")
print(classmethod(Animal))

printl("staticmethod")
print(staticmethod(Animal))

=== input ===
hia
a
=== print ===
a b c$
=== globals ===
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10c090cd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/luckyfang/PycharmProjects/pyStudy/innerfunc/base_inner.py', '__cached__': None, 'math': <module 'math' from '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload/math.cpython-39-darwin.so'>, 'random': <module 'random' from '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py'>, 'printl': <function printl at 0x10c0dc160>, 'a': 10, 'b': (20, 18, 19, 22), 'lst': range(0, 10), 'l1': ['tom', 'jack', 'alice', 'eric'], 'l2': [20, 18, 19, 22, 20], 'zipped': <zip object at 0x10e19a9c0>, 'os': <module 'os' from '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py'>, 'str1': '我叫fang,我今年22岁了', 'Animal': <class '__main__.Animal'>, 'Dog': <class '__main__.Dog'>, 'view': <memory at 0x10e169a00>, 'item': 45, 'sl': slice(None, 3, None), 'ob': <object object at 0x10e026fe0>}
=== locals ===
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10c090cd0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/luckyfang/PycharmProjects/pyStudy/innerfunc/base_inner.py', '__cached__': None, 'math': <module 'math' from '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload/math.cpython-39-darwin.so'>, 'random': <module 'random' from '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py'>, 'printl': <function printl at 0x10c0dc160>, 'a': 10, 'b': (20, 18, 19, 22), 'lst': range(0, 10), 'l1': ['tom', 'jack', 'alice', 'eric'], 'l2': [20, 18, 19, 22, 20], 'zipped': <zip object at 0x10e19a9c0>, 'os': <module 'os' from '/usr/local/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py'>, 'str1': '我叫fang,我今年22岁了', 'Animal': <class '__main__.Animal'>, 'Dog': <class '__main__.Dog'>, 'view': <memory at 0x10e169a00>, 'item': 45, 'sl': slice(None, 3, None), 'ob': <object object at 0x10e026fe0>}
=== __import__ ===
4.47213595499958
=== open ===
=== compile ===
<code object <module> at 0x10e1dc450, file "", line 1>
=== eval ===
7
=== exec ===
a= 7
=== repr ===
<class '__main__.Animal'>
=== property ===
<property object at 0x10e1be400>
=== classmethod ===
<classmethod object at 0x10df24460>
=== staticmethod ===
<staticmethod object at 0x10df24460>

标准函数

特点: 直接导入

import math

print(math.sqrt(16))

第三方函数

特点: 要先安装,然后再导入使用

pip install requests
import requests

resp =  requests.get("http://www.baidu.com/")
print(resp)

自定义函数

特点: 自己定义的函数,固定写法没什么好说的

def funcName(parmas):
  funcBody
  • funcName: 函数名
  • parmas: 参数
  • funcBody: 函数体
def sayHello(name):
  print("你好,",name)
  
sayHello("jack")

对比C函数

int sum(int a, int b){
  return a+b;
}
def sun(a,b):
  return a+b

其实还是蛮像的,毕竟 天下乌鸦一般黑

因为python是脚本语言不需要写参数类型,同时也不需要显式声明返回值.

lambda(匿名函数)

注意:lambda匿名函数适合于写简短的函数,如果方法体内较多行,则lambda表达式不适用。

lambda params:expr;
  • params:参数
  • expr:语句