zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python学习笔记(七)——内置函数

Python笔记学习 函数 内置
2023-09-27 14:28:31 时间

builtins.py模块,是python的内建模块,在运行时会自动导入该模块。在该模块中定义了很多我们常用的内置函数,比如print,input 等。

在 builtins.py 模块中给出如下注释的文档字符串

Built-in functions, exceptions, and other objects.
内置函数,异常和其他对象。

该模块会在python 程序运行时自动导入,因此我们在没有导入任何模块的情况下可以使用 input 输入,使用 print 输出。我们通过 dir() 可以查看当前程序(.py 文件)引用的变量、方法和定义的类型列表。

>>> dir()
['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'sys']

其中在 builtins.py 中定义了很多的内置函数,我们可以通过 print(fun_name.__doc__) 打印出函数的文档字符串查看函数文档。

例如:

>>> print(print.__doc__)
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.

另外,也可以通过 help(函数名) 查看函数的相关信息。详细用法请参考目录中 help() 函数。

下面让我们通过一些简单🌰(例子) 来认识这些函数。 注:以下实例模拟交互界面进行测试。


print()

def print(self, *args, sep=' ', end='\n', file=None)

print 实例。print 的 file 参数可以指向一个文件句柄(文件描述符),而后直接输出的文件。

>>> print(11,22,33) 		# 输出任意类型, ','默认为空格
11 22 33
>>> print("hello"+"world")	# ➕ 可以连接两个字符串
helloworld
>>> print(10,20,sep="#")	# 设置 ‘,’ 分割符的值,默认是一个空格
10#20
>>> print(10,20,end="。")	# 设置 print 打印结束后的输出内容,默认为换行('\n')
10 20。

除此之外,print(r"string")... 还支持 r'', b'', u'', f'' 等特殊参数
r'string\n' # 非转义原生字符串		==》 输出:string\n
b'bytes'	# bytes字节符,打印以b开头,通过 encode() 与 decode() 转换
u/U:        # 表示unicode字符串,通过 encoding() 设置编码
f/format()	# 格式化操作

input()

def input(“提示信息”)

input实例,接受输入,返回一个字符串。

>>> a=input("输入")	# 在 “xxx” 的内容为提示信息
输入>? 12
>>> type(a)
<class 'str'>

max()

def max(*args, key=None)

max()实例。根据参数的 Unicode(ascii)码比较,返回其中最大的一个。

>>> max(11,22,33)
33
# 对于复合型的列表,如[(),()]或[[],[]]等可以通过以下方式指定比较方式
>>> lst=[[12,34,56],[22,22,22],[10,30,80]]
>>> max(lst)			# 默认以第一维的数值进行比较,即每个小列表的第一个数。
[22, 22, 22]
>>> max(lst,key=lambda x:x[1])	# 以小列表的第二维进行比较,输出其中较大的小列表
[12, 34, 56]
>>> max(lst,key=lambda x:x[1])	# 以小列表的第三维进行比较,...
[12, 34, 56]

min()

def min(*args, key=None)

与 max() 用法相同。


len()

def len(*args, **kwargs)

len()实例。返回对象(字符、列表、元组等)长度或项目个数

>>> str="hello"		# 字符串
>>> len(str)
5
>>> t=(1,2,3,4)		# 元组
>>> len(t)
4
>>> st={1,2,3,4}	# 集合
>>> len(st)
4
>>> dt = {"key1" : 1, "key2" : 2 }	# 字典
>>> len(dt)
2
...
# 如果是自定义类型,在类中重写 len() 函数即可。

type()

def __init__(cls, what, bases=None, dict=None)

type()实例。返回对象类型名称。

>>> type(1)
<class 'int'>
>>> a=[1,2,3,4]
>>> type(a)
<class 'list'>

isinstance()

def isinstance(x, A_tuple)

isinstance()实例。返回一个 bool 类型。

>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(str,list,int))           
True

id()

def id(*args, **kwargs)

id()实例。返回数据在内存中的地址。

>>> id(1)
140732958299168
>>> a=1
>>> id(a)
140732958299168

int()

def __init__(self, x, base=10)

int()实例。将数据类型转换为整型。

>>> int(1.2)			# 浮点数 ==》 整型
1
>>> int("2")			# 字符串 ==》 整型
2
>>> int("0b1010",2)		# 二进制 ==》 整型
10
>>> int("0o12",8)		# 八进制 ==》 整型
10
>>> int("0xa",16)		# 十六进制 =》 整型
10

除此之外还有类似的函数,如:

bin()

oct()

hex()

“”“
def bin(*args, **kwargs)
def oct(*args, **kwargs)
def hex(*args, **kwargs)
”“”
>>> bin(10)				'0b1010'
>>> bin(0o12)			'0b1010'
>>> bin(0xa)			'0b1010'
>>> oct(0b1010)			'0o12'
>>> oct(10)				'0o12'
>>> oct(0xa)			'0o12'
>>> hex(0b1010)			'0xa'
>>> hex(0o12)			'0xa'
>>> hex(10)				'0xa'

float()

def __init__(self, *args, **kwargs)

float()实例。将数据类型转换为浮点型。

>>> float(1)
1.0
>>> float("2")
2.0

str()

def __init__(self, value='', encoding=None, errors='strict')

str()实例。将数据类型转换为 str 类型

>>> str(1)				'1'
>>> str([11,22])		'[11, 22]'
>>> str((1,2,3,4))		'(1, 2, 3, 4)'
>>> str(({1,2,3,4}))	'{1, 2, 3, 4}'

bool()

def __init__(self, x)

bool()实例。将参数转换为布尔类型,如果没有参数,返回 False

>>> bool(0)				False
>>> bool([])			False
>>> bool((0))			False
>>> bool({})			False
>>> bool(None)			False

list()

def __init__(self, seq=())

list()实例。将给定数据类型转换为列表。

>>> list((1,2,3,4))			[1, 2, 3, 4]
>>> list("hello")			['h', 'e', 'l', 'l', 'o']
>>> list({"hello":1,"python":2}) # 默认使用字典的 keys 转换为列表
['hello', 'python']
>>> list({"hello":1,"python":2}.values()) # 使用字典的 values 转换为列表
[1, 2]

tuple()

def __init__(self, seq=())

tuple() 与 list() 用法相同。


dict()

def __init__(self, seq=None, **kwargs)

dict()实例。使用关键字参数生成字典。

>>> dict(name="张三",age="18")
{'name': '张三', 'age': '18'}

set()

def __init__(self, seq=())

set()实例。set 集合中无重复元素,常用来进行去重操作。

>>> lst=[1,2,1,3,4]
>>> list(set(lst))
[1, 2, 3, 4]
>>> tup=(1,2,3,2,1)
>>> tuple(set(tup))
(1, 2, 3)

round()

def round(*args, **kwargs)

round()实例。数字四舍五入到给定的十进制精度。

>>> round(3.14)
3

abs()

def abs(*args, **kwargs)

abs()实例。返回参数的绝对值。

>>> abs(-1)
1
>>> abs(-3.14)
3.14

pow()

def pow(*args, **kwargs)

pow()实例。两个参数返回 xy,三个参数返回 xy % z 。

>>> pow(2,3)			# 2**3==8
8
pow(2,3,5)				# 2**3%5==8%5==3
3

divmod()

def divmod(x, y)

divmod()实例。返回 10/3 的元组,(10//3,10%3)即(商,余数)。

>>> divmod(10,3)
(3, 1)
>>> 10//3
3
>>> 10%3
1

help()

查看指定对象的帮助信息
help()实例

>>> help(help)
Help on _Helper in module _sitebuiltins object:
class _Helper(builtins.object)
 |  Define the builtin 'help'.
 |  
 |  This is a wrapper around pydoc.help that provides a helpful message
 |  when 'help' is typed at the Python interactive prompt.
 |  
 |  Calling help() at the Python prompt starts an interactive help session.
 |  Calling help(thing) prints help for the python object 'thing'.
 |  
 |  Methods defined here:
 # 。。。 以下内容省略

>>> help(print)
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.


sum()

def sum(*args, **kwargs)

sum()实例。返回可迭代对象相加的结果

>>> sum([11,22,33])
66
>>> sum((11,22,33))
66
>>> sum((11,22,33),100)
166

dir()

def dir(p_object=None)

dir()实例。列出指定对象的属性信息

>>> dir()
['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'dt', 'lst', 'sys', 'tup']

bytes()

def __init__(self, value=b'', encoding=None, errors='strict')

bytes()实例。把字符转为bytes

>>> "我爱中国".encode("utf-8")
b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'
>>> bytes("我爱中国",encoding="utf-8")
b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'

>>> b'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'.decode("utf-8")
'我爱中国'

all()

def all(*args, **kwargs)

all()实例。判断的可迭代对象的每个元素是否都为True值.返回布尔类型。

>>> all([11,22,33])				True
>>> all([11,22,33,0])			False
>>> all([11,22,33,[]])			False

any()

def any(*args, **kwargs)

any()实例。判断可迭代对象的元素是否有为True值的元素,返回布尔类型。

>>> all([0,[]])				False
>>> all([0,[],1])			False

enumerate()

def __init__(self, iterable, start=0)

enumerate()实例。用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个素引
序列。同时列出数据数据下标

>>>for i in enumerate([11,22,33]):
...     print(i)
...    
(0, 11)
(1, 22)
(2, 33)

zip()

def __init__(self, iter1, iter2=None, *some)

zip()实例。合并多个序列类型

>>> zip([1,2,3,4],["a","b","c","d"])
<zip object at 0x0000022C1C697E08>

# 使用列表接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>> z=zip([1,2,3,4],["a","b"])	# 参数不完整
>>> list(z)
[(1, 'a'), (2, 'b')]

# 使用元组接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> tuple(z)
((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))

# 使用字典接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> dict(z)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

# 使用集合接收
>>> z=zip([1,2,3,4],["a","b","c","d"])
>>> set(z)
{(1, 'a'), (4, 'd'), (2, 'b'), (3, 'c')}

filter()

 def __init__(self, function_or_None, iterable)

filter()实例。过滤器。根据提供的函数返回为真的生成一个新序列

>>> lst=[1,2,3,4,5,6]
>>> newlst=filter(lambda x:x%2==0,lst)	# 过滤奇数
>>> type(newlst)
<class 'filter'>
>>> list(newlst)
[2, 4, 6]

map()

def __init__(self, func, *iterables)

map()实例。映射器。根据提供的函数对指定序列做映射。

>>> tmp=map(lambda x:x+1,[1,2,3,4])
>>> type(tmp)
<class 'map'>
>>> list(tmp)
[2, 3, 4, 5]

>>> tmp=map(lambda x,y:x+y,[1,1,1],[2,2,2])
>>> list(tmp)
[3, 3, 3]

sorted()

def sorted(*args, **kwargs)

sorted()实例。对指定序列进行排序。

>>> sorted([1,8,3,3,6,2]) # 默认升序排列
[1, 2, 3, 3, 6, 8]
>>> sorted([1,8,3,3,6,2],reverse=True) 	# 降序排列
[8, 6, 3, 3, 2, 1]

# 对字典排序
>>> dt={"Mon.":1,"Sun.":7,"Tue.":2,"Fri.":5,}
>>> sorted(dt.items(),key=lambda x:x[1])	# 对 value 值排序
[('Mon.', 1), ('Tue.', 2), ('Fri.', 5), ('Sun.', 7)]
>>> sorted(dt.items(),key=lambda x:x[0])	# 对 key 值排序
[('Fri.', 5), ('Mon.', 1), ('Sun.', 7), ('Tue.', 2)]

callable()

def callable(i_e_, some_kind_of_function)

callable()实例。用来检测对象是否可被调用,返回布尔型。

>>> a=1
>>> callable(a)
False
>>> def fun():
...     pass
>>> callable(fun)
True

globals()

def globals(*args, **kwargs)

globals()实例。以字典格式返回当前位置的全部全局。

>>> gdt=globals()
>>> gdt
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001E4C4477208>, '__spec__': None, '__file__': '<input>', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <bound method ImportHookManager.do_import of <module '_pydev_bundle.pydev_import_hook.import_hook'>>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'WindowsError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-Z plus Return to exit, 'exit': Use exit() or Ctrl-Z plus Return to exit, 'copyright': Copyright (c) 2001-2018 Python Software Foundation.
All Rights Reserved.

# 检测是否存在全局 g_lst
>>> if 'g_lst'in gdt.keys():print("存在")
... else:print("不存在")
不存在
>>> g_lst=[1,2,3]		# 添加全局变量 h_lst
>>> gdt=globals()
>>> if 'g_lst'in gdt.keys():print("存在")
... else:print("不存在")
存在

locals()

def locals(*args, **kwargs)

locals()实例。返回本地作用域中的所有名字。返回字典类型。

>>> def func(a,b):
...     print(locals())
...    
>>> func(11,22)
{'a': 11, 'b': 22}

getattr()

def getattr(object, name, default=None)

getattr()实例。函数用于返回一个对象属性值。

>>> a=[11,22,33]
>>> getattr(a,"append")		# 返回对象a的 append 属性
<built-in method append of list object at 0x000001E4C71A03C8>
>>> getattr(a,"append")(50)	# 用户对象的属性
>>> a
[11, 22, 33, 50]

hasattr()

def hasattr(*args, **kwargs)

hasattr()实例。用于判断对象是否包含对应的属性。

>>> a=[11,22,33]
>>> hasattr(a,"end")
False
>>> hasattr(a,"append")
True

delattr()

def delattr(x, y)

delattr()实例。用于删除属性。delattr(x, ‘foobar’) 相等于 del x.foobar。

>>> class test:
...     x=1
...     y=2
...     z=3
...    
>>> ts=test()
>>> hasattr(ts,"z")
True
>>> delattr(test,"z")
>>> hasattr(ts,"z")
False

setattr()

def setattr(x, y, v)

setattr()实例。对应函数 getattr(),用于设置属性值,该属性不一定是存在的。

>>> class test:
...     x=1
...     y=2
...     z=3
...    
>>> ts=test()
>>> getattr(ts,"z")
3
>>> setattr(ts,"z",10)
>>> getattr(ts,"z")
10
>>> ts.z
10

iter()

def iter(source, sentinel=None)

iter()实例。用于生成迭代器。

>>> a
[11, 22, 33, 50]
>>> type(a)
<class 'list'>
>>> a=iter(a)		# 生成迭代器
>>> type(a)
<class 'list_iterator'>
>>> next(a)			# 获取元素
11
>>> next(a)
22
>>> next(a)
33

next()

返回可迭代的下一个元素值。


super()

def __init__(self, type1=None, type2=None)

super()实例。用于调用父类(超类)中的方法。

>>> class A:
...     def add(self, x):
...         y = x + 1
...         print(y)
... 
>>> class B(A):
...     def add(self, x):
...         super().add(x)
...         
>>> b=B()
>>> b.add(2)
3