python學習筆記(七)——內置函數

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章