ython文檔資源包括下面幾種:
序號 | 形式 | 描述 |
1 | #注釋 | 程序語句對應的注釋 |
2 | dir() | 查看對象全部屬性 |
3 | doc | 文檔字符串 |
4 | help() | 查看對象具體屬性用法 |
5 | HTML報表 | html格式幫助文檔 |
6 | 標準手冊 | python語言和庫的說明 |
7 | 網站資源 | 在線教程、技術博客 |
8 | 書籍資源 | 相關書籍 |
python井號(#)用于程序語句對應的注釋。
#號后面直到行末的內容都會當做注釋,不被執(zhí)行。
python通過#注釋的內容只能在程序原文件查看。
python的dir(對象)內置函數,返回對象全部屬性組成的列表。
示例
# 通過常量表達式生成實例后查看
>>> dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 通過類型名生成實例后查看
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir('')==dir(str)
python文檔字符串doc,值為模塊文件開頭、函數開頭、類開頭、方法開頭的注釋,python會自動封裝這些注釋,并且保存在doc。這些注釋寫在三引號內。
文檔字符串可以通過不同位置路徑對象的doc獲取。
不同路徑對象屬性名(函數名、類名、方法名)可以通過dir(模塊)獲取。
模塊:模塊名.doc
函數:模塊名.函數名.doc
類:模塊名.類名.doc
方法名:模塊名.類名.方法名.doc
示例
'''
模塊文件名:docstr.py
模塊開頭的文檔字符串
'''
S='梯閱線條'
def hellof(name):
'''
函數開頭的文檔字符串
'''
print('hello ',name)
class Student:
'''
類開頭處的文檔字符串
'''
def study(self):
'''
方法開頭的文檔字符串
'''
pass
# 查看不同對象的__doc__文檔字符串
>>> path=r'E:\documents\F盤'
>>> import os
>>> os.chdir(path)
>>> import docstr
>>> dir(docstr)
['L', 'S', 'Student', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'hellof']
>>> print(docstr.__doc__)
模塊文件名:docstr.py
模塊開頭的文檔字符串
>>> print(docstr.hellof.__doc__)
函數開頭的文檔字符串
>>> print(docstr.Student.__doc__)
類開頭處的文檔字符串
>>> print(docstr.Student.study.__doc__)
方法開頭的文檔字符串
python的help()內置函數查看傳入對象的使用說明,傳入對象可以是模塊名、函數名、類名、方法名、變量引用。
示例
>>> path=r'E:\documents\F盤'
>>> import os
>>> os.chdir(path)
>>> import docstr
>>> help(docstr)
Help on module docstr:
NAME
docstr
DESCRIPTION
模塊文件名:docstr.py
模塊開頭的文檔字符串
CLASSES
builtins.object
Student
class Student(builtins.object)
| 類開頭處的文檔字符串
|
| Methods defined here:
|
| study(self)
| 方法開頭的文檔字符串
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
FUNCTIONS
hellof(name)
函數開頭的文檔字符串
DATA
L = ['梯', '閱', '線', '條']
S = '梯閱線條'
FILE
e:\documents\f盤\docstr.py
>>> help(docstr.hellof)
Help on function hellof in module docstr:
hellof(name)
函數開頭的文檔字符串
用法
python -m pydoc -w docstr
描述
進入到docstr.py文件的目錄,執(zhí)行用法里面的語句。
執(zhí)行pydoc模塊,將docstr的文檔字符串寫入到docstr.html文件,成為幫助文檔。
-m:表示運行模塊(module),后面接模塊名
-w:后接要生成html文檔的模塊名,表示將模塊的文檔字符串寫入到模塊名.html文件中。
示例
E:\documents\F盤>python -m pydoc -w docstr
wrote docstr.html
會生成類似下面的html文件內容:
python安裝目錄的doc目錄下python378.chm。
更多內容參考python知識分享或軟件測試開發(fā)目錄。
需要安裝Python的可參考:Python3.8.6 + PyCharm 環(huán)境安裝 + PyCharm使用
字符串是 Python 最常用的數據類型。
我們可以使用引號( ' 或 ",甚至 """ 或 ''' 均可 )來創(chuàng)建字符串。
不廢話,看下面的實例。
print('技術好奇心,分享技術,一起學習呦^_^')
結果:
源:pypypypy
www.cnblogs.com/pypypy/p/12011506.html
內置函數就是python給你提供的, 拿來直接用的函數,比如print.,input等。截止到python版本3.6.2 python一共提供了68個內置函數。
#68個內置函數
# abs dict help min setattr
# all dir hex next slice
# any divmod id object sorted
# ascii enumerate input oct staticmethod
# bin eval int open str
# bool exec isinstance ord sum
# bytearray ?lter issubclass pow super
# bytes ?oat iter print tuple
# callable format len property type
# chr frozenset list range vars
# classmethod getattr locals repr zip
# compile globals map reversed __import__
# complex hasattr max round
# delattr hash memoryview set
和數字相關
1. 數據類型
bool : 布爾型(True,False)
int : 整型(整數)
float : 浮點型(小數)
complex : 復數
2. 進制轉換
bin 將給的參數轉換成二進制
otc 將給的參數轉換成八進制
hex 將給的參數轉換成十六進制
print(bin(10)) # 二進制:0b1010
print(hex(10)) # 十六進制:0xa
print(oct(10)) # 八進制:0o12
3. 數學運算
abs 返回絕對值
divmode 返回商和余數
round 四舍五入
pow(a, b) 求a的b次冪, 如果有三個參數. 則求完次冪后對第三個數取余
sum 求和
min 求最小值
max 求最大值
print(abs(-2)) # 絕對值:2
print(divmod(20,3)) # 求商和余數:(6,2)
print(round(4.50)) # 五舍六入:4
print(round(4.51)) #5
print(pow(10,2,3)) # 如果給了第三個參數. 表示最后取余:1
print(sum([1,2,3,4,5,6,7,8,9,10])) # 求和:55
print(min(5,3,9,12,7,2)) #求最小值:2
print(max(7,3,15,9,4,13)) #求最大值:15
和數據結構相關
1. 序列
(1)列表和元組
list 將一個可迭代對象轉換成列表
tuple 將一個可迭代對象轉換成元組
print(list((1,2,3,4,5,6))) #[1, 2, 3, 4, 5, 6]
print(tuple([1,2,3,4,5,6])) #(1, 2, 3, 4, 5, 6)
(2)相關內置函數
reversed 將一個序列翻轉, 返回翻轉序列的迭代器
slice 列表的切片
lst = "你好啊"
it = reversed(lst) # 不會改變原列表. 返回一個迭代器, 設計上的一個規(guī)則
print(list(it)) #['啊', '好', '你']
lst = [1, 2, 3, 4, 5, 6, 7]
print(lst[1:3:1]) #[2,3]
s = slice(1, 3, 1) # 切片用的
print(lst[s]) #[2,3]
(3)字符串
str 將數據轉化成字符串
print(str(123)+'456') #123456
format 與具體數據相關, 用于計算各種小數, 精算等.
s = "hello world!"
print(format(s, "^20")) #劇中
print(format(s, "<20")) #左對齊
print(format(s, ">20")) #右對齊
# hello world!
# hello world!
# hello world!
print(format(3, 'b' )) # 二進制:11
print(format(97, 'c' )) # 轉換成unicode字符:a
print(format(11, 'd' )) # ?進制:11
print(format(11, 'o' )) # 八進制:13
print(format(11, 'x' )) # 十六進制(?寫字母):b
print(format(11, 'X' )) # 十六進制(大寫字母):B
print(format(11, 'n' )) # 和d?樣:11
print(format(11)) # 和d?樣:11
print(format(123456789, 'e' )) # 科學計數法. 默認保留6位小數:1.234568e+08
print(format(123456789, '0.2e' )) # 科學計數法. 保留2位小數(小寫):1.23e+08
print(format(123456789, '0.2E' )) # 科學計數法. 保留2位小數(大寫):1.23E+08
print(format(1.23456789, 'f' )) # 小數點計數法. 保留6位小數:1.234568
print(format(1.23456789, '0.2f' )) # 小數點計數法. 保留2位小數:1.23
print(format(1.23456789, '0.10f')) # 小數點計數法. 保留10位小數:1.2345678900
print(format(1.23456789e+3, 'F')) # 小數點計數法. 很大的時候輸出INF:1234.567890
bytes 把字符串轉化成bytes類型
bs = bytes("今天吃飯了嗎", encoding="utf-8")
print(bs) #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'
bytearray 返回一個新字節(jié)數組. 這個數字的元素是可變的, 并且每個元素的值得范圍是[0,256)
ret = bytearray("alex" ,encoding ='utf-8')
print(ret[0]) #97
print(ret) #bytearray(b'alex')
ret[0] = 65 #把65的位置A賦值給ret[0]
print(str(ret)) #bytearray(b'Alex')
ord 輸入字符找?guī)ё址幋a的位置
chr 輸入位置數字找出對應的字符
ascii 是ascii碼中的返回該值 不是就返回u
print(ord('a')) # 字母a在編碼表中的碼位:97
print(ord('中')) # '中'字在編碼表中的位置:20013
print(chr(65)) # 已知碼位,求字符是什么:A
print(chr(19999)) #丟
for i in range(65536): #打印出0到65535的字符
print(chr(i), end=" ")
print(ascii("@")) #'@'
repr 返回一個對象的string形式
s = "今天\n吃了%s頓\t飯" % 3
print(s)#今天# 吃了3頓 飯
print(repr(s)) # 原樣輸出,過濾掉轉義字符 \n \t \r 不管百分號%
#'今天\n吃了3頓\t飯'
2. 數據集合
字典:dict 創(chuàng)建一個字典
集合:set 創(chuàng)建一個集合
frozenset 創(chuàng)建一個凍結的集合,凍結的集合不能進行添加和刪除操作。
3. 相關內置函數
len 返回一個對象中的元素的個數
sorted 對可迭代對象進行排序操作 (lamda)
語法:sorted(Iterable, key=函數(排序規(guī)則), reverse=False)
Iterable: 可迭代對象
key: 排序規(guī)則(排序函數), 在sorted內部會將可迭代對象中的每一個元素傳遞給這個函數的參數. 根據函數運算的結果進行排序
reverse: 是否是倒敘. True: 倒敘, False: 正序
lst = [5,7,6,12,1,13,9,18,5]
lst.sort # sort是list里面的一個方法
print(lst) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
ll = sorted(lst) # 內置函數. 返回給你一個新列表 新列表是被排序的
print(ll) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
l2 = sorted(lst,reverse=True) #倒序
print(l2) #[18, 13, 12, 9, 7, 6, 5, 5, 1]
#根據字符串長度給列表排序
lst = ['one', 'two', 'three', 'four', 'five', 'six']
def f(s):
return len(s)
l1 = sorted(lst, key=f, )
print(l1) #['one', 'two', 'six', 'four', 'five', 'three']
enumerate 獲取集合的枚舉對象
lst = ['one','two','three','four','five']
for index, el in enumerate(lst,1): # 把索引和元素一起獲取,索引默認從0開始. 可以更改
print(index)
print(el)
# 1
# one
# 2
# two
# 3
# three
# 4
# four
# 5
# five
all 可迭代對象中全部是True, 結果才是True
any 可迭代對象中有一個是True, 結果就是True
print(all([1,'hello',True,9])) #True
print(any([0,0,0,False,1,'good'])) #True
zip 函數用于將可迭代的對象作為參數, 將對象中對應的元素打包成一個元組, 然后返回由這些元組組成的列表. 如果各個迭代器的元素個數不一致, 則返回列表長度與最短的對象相同
lst1 = [1, 2, 3, 4, 5, 6]
lst2 = ['醉鄉(xiāng)民謠', '驢得水', '放牛班的春天', '美麗人生', '辯護人', '被嫌棄的松子的一生']
lst3 = ['美國', '中國', '法國', '意大利', '韓國', '日本']
print(zip(lst1, lst1, lst3)) #<zip object at 0x00000256CA6C7A88>
for el in zip(lst1, lst2, lst3):
print(el)
# (1, '醉鄉(xiāng)民謠', '美國')
# (2, '驢得水', '中國')
# (3, '放牛班的春天', '法國')
# (4, '美麗人生', '意大利')
# (5, '辯護人', '韓國')
# (6, '被嫌棄的松子的一生', '日本')
fiter 過濾 (lamda)
語法:fiter(function. Iterable)
function: 用來篩選的函數. 在?lter中會自動的把iterable中的元素傳遞給function. 然后根據function返回的True或者False來判斷是否保留留此項數據 , Iterable: 可迭代對象
def func(i): # 判斷奇數
return i % 2 == 1
lst = [1,2,3,4,5,6,7,8,9]
l1 = filter(func, lst) #l1是迭代器
print(l1) #<filter object at 0x000001CE3CA98AC8>
print(list(l1)) #[1, 3, 5, 7, 9]
map 會根據提供的函數對指定序列列做映射(lamda)
語法 : map(function, iterable)
可以對可迭代對象中的每一個元素進行映射. 分別去執(zhí)行 function
def f(i): return i
lst = [1,2,3,4,5,6,7,]
it = map(f, lst) # 把可迭代對象中的每一個元素傳遞給前面的函數進行處理. 處理的結果會返回成迭代器print(list(it)) #[1, 2, 3, 4, 5, 6, 7]
和作用域相關
locals 返回當前作用域中的名字
globals 返回全局作用域中的名字
def func:
a = 10
print(locals) # 當前作用域中的內容
print(globals) # 全局作用域中的內容
print("今天內容很多")
func
# {'a': 10}
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
# <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>,
# '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'
# (built-in)>, '__file__': 'D:/pycharm/練習/week03/new14.py', '__cached__': None,
# 'func': <function func at 0x0000026F8D6B97B8>}
# 今天內容很多
和迭代器/生成器相關
range 生成數據
next 迭代器向下執(zhí)行一次, 內部實際使?用了__ next__?方法返回迭代器的下一個項目
iter 獲取迭代器, 內部實際使用的是__ iter__?方法來獲取迭代器
for i in range(15,-1,-5):
print(i)
# 15
# 10
# 5
# 0
lst = [1,2,3,4,5]
it = iter(lst) # __iter__獲得迭代器
print(it.__next__) #1
print(next(it)) #2 __next__
print(next(it)) #3
print(next(it)) #4
字符串類型代碼的執(zhí)行
eval 執(zhí)行字符串類型的代碼. 并返回最終結果
exec 執(zhí)行字符串類型的代碼
compile 將字符串類型的代碼編碼. 代碼對象能夠通過exec語句來執(zhí)行或者eval進行求值
s1 = input("請輸入a+b:") #輸入:8+9
print(eval(s1)) # 17 可以動態(tài)的執(zhí)行代碼. 代碼必須有返回值
s2 = "for i in range(5): print(i)"
a = exec(s2) # exec 執(zhí)行代碼不返回任何內容
# 0
# 1
# 2
# 3
# 4
print(a) #None
# 動態(tài)執(zhí)行代碼
exec("""
def func:
print(" 我是周杰倫")
""" )
func #我是周杰倫
code1 = "for i in range(3): print(i)"
com = compile(code1, "", mode="exec") # compile并不會執(zhí)行你的代碼.只是編譯
exec(com) # 執(zhí)行編譯的結果
# 0
# 1
# 2
code2 = "5+6+7"
com2 = compile(code2, "", mode="eval")
print(eval(com2)) # 18
code3 = "name = input('請輸入你的名字:')" #輸入:hello
com3 = compile(code3, "", mode="single")
exec(com3)
print(name) #hello
輸入輸出
print : 打印輸出
input : 獲取用戶輸出的內容
print("hello", "world", sep="*", end="@") # sep:打印出的內容用什么連接,end:以什么為結尾
#hello*world@
內存相關
hash : 獲取到對象的哈希值(int, str, bool, tuple). hash算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空間換的時間 比較耗費內存
s = 'alex'
print(hash(s)) #-168324845050430382
lst = [1, 2, 3, 4, 5]
print(hash(lst)) #報錯,列表是不可哈希的
id : 獲取到對象的內存地址
s = 'alex'
print(id(s)) #2278345368944
文件操作相關
open : 用于打開一個文件, 創(chuàng)建一個文件句柄
f = open('file',mode='r',encoding='utf-8')
f.read
f.close
模塊相關
__ import__ : 用于動態(tài)加載類和函數
# 讓用戶輸入一個要導入的模塊
import os
name = input("請輸入你要導入的模塊:")
__import__(name) # 可以動態(tài)導入模塊
幫 助
help : 函數用于查看函數或模塊用途的詳細說明
print(help(str)) #查看字符串的用途
調用相關
callable : 用于檢查一個對象是否是可調用的. 如果返回True, object有可能調用失敗, 但如果返回False. 那調用絕對不會成功
a = 10
print(callable(a)) #False 變量a不能被調用
#
def f:
print("hello")
print(callable(f)) # True 函數是可以被調用的
查看內置屬性
dir : 查看對象的內置屬性, 訪問的是對象中的__dir__方法
print(dir(tuple)) #查看元組的方法
*請認真填寫需求信息,我們會在24小時內與您取得聯系。