天天看點

python基礎——内置函數

python基礎——内置函數

 一、内置函數(python3.x)

python基礎——内置函數

内置參數詳解官方文檔: https://docs.python.org/3/library/functions.html?highlight=built#ascii 

一、數學運算類

abs(x)

求絕對值

1、參數可以是整型,也可以是複數

2、若參數是負數,則傳回負數的模

complex([real[, imag]]) 建立一個複數
divmod(a, b)

分别取商和餘數

注意:整型、浮點型都可以

float([x]) 将一個字元串或數轉換為浮點數。如果無參數将傳回0.0
int([x[, base]])  将一個字元轉換為int類型,base表示進制
long([x[, base]])  将一個字元轉換為long類型
pow(x, y[, z])  傳回x的y次幂
range([start], stop[, step])  産生一個序列,預設從0開始
round(x[, n])  四舍五入
sum(iterable[, start])  對集合求和
oct(x) 将一個數字轉化為8進制
hex(x) 将整數x轉換為16進制字元串
chr(i) 傳回整數i對應的ASCII字元
bin(x) 将整數x轉換為二進制字元串
bool([x]) 将x轉換為Boolean類型

二、集合類操作

basestring()

str和unicode的超類

不能直接調用,可以用作isinstance判斷

format(value [, format_spec])

格式化輸出字元串

格式化的參數順序從0開始,如“I am {0},I like {1}”

unichr(i) 傳回給定int類型的unicode
enumerate(sequence [, start = 0]) 傳回一個可枚舉的對象,該對象的next()方法将傳回一個tuple
iter(o[, sentinel]) 生成一個對象的疊代器,第二個參數表示分隔符
max(iterable[, args...][key])  傳回集合中的最大值
min(iterable[, args...][key]) 傳回集合中的最小值
dict([arg]) 建立資料字典
list([iterable])  将一個集合類轉換為另外一個集合類
set() set對象執行個體化
frozenset([iterable]) 産生一個不可變的set
str([object])  轉換為string類型
sorted(iterable[, cmp[, key[, reverse]]])  隊集合排序
tuple([iterable])  生成一個tuple類型
xrange([start], stop[, step])  xrange()函數與range()類似,但xrnage()并不建立清單,而是傳回一個xrange對象,它的行為與清單相似,但是隻在需要時才計算清單值,當清單很大時,這個特性能為我們節省記憶體

三、邏輯判斷

all(iterable)

1、集合中的元素都為真的時候為真

2、特别的,若為空串傳回為True

any(iterable)

1、集合中的元素有一個為真的時候為真

2、特别的,若為空串傳回為False

cmp(x, y) 如果x < y ,傳回負數;x == y, 傳回0;x > y,傳回正數

四、反射

callable(object)

檢查對象object是否可調用

1、類是可以被調用的

2、執行個體是不可以被調用的,除非類中聲明了__call__方法

classmethod()

1、注解,用來說明這個方式是個類方法

2、類方法即可被類調用,也可以被執行個體調用

3、類方法類似于Java中的static方法

4、類方法中不需要有self參數

compile(source, filename, mode[, flags[, dont_inherit]])

将source編譯為代碼或者AST對象。代碼對象能夠通過exec語句來執行或者eval()進行求值。

1、參數source:字元串或者AST(Abstract Syntax Trees)對象。

2、參數 filename:代碼檔案名稱,如果不是從檔案讀取代碼則傳遞一些可辨認的值。

3、參數model:指定編譯代碼的種類。可以指定為 ‘exec’,’eval’,’single’。

4、參數flag和dont_inherit:這兩個參數暫不介紹

dir([object])

1、不帶參數時,傳回目前範圍内的變量、方法和定義的類型清單;

2、帶參數時,傳回參數的屬性、方法清單。

3、如果參數包含方法__dir__(),該方法将被調用。當參數為執行個體時。

4、如果參數不包含__dir__(),該方法将最大限度地收集參數資訊

delattr(object, name) 删除object對象名為name的屬性
eval(expression [, globals [, locals]]) 計算表達式expression的值
execfile(filename [, globals [, locals]]) 用法類似exec(),不同的是execfile的參數filename為檔案名,而exec的參數為字元串。
filter(function, iterable)

構造一個序列,等價于[ item for item in iterable if function(item)]

1、參數function:傳回值為True或False的函數,可以為None

2、參數iterable:序列或可疊代對象

getattr(object, name [, defalut]) 擷取一個類的屬性
globals() 傳回一個描述目前全局符号表的字典
hasattr(object, name) 判斷對象object是否包含名為name的特性
hash(object) 如果對象object為哈希表類型,傳回對象object的哈希值
id(object) 傳回對象的唯一辨別
isinstance(object, classinfo) 判斷object是否是class的執行個體
issubclass(class, classinfo) 判斷是否是子類
len(s)  傳回集合長度
locals()  傳回目前的變量清單
map(function, iterable, ...)  周遊每個元素,執行function操作
memoryview(obj)  傳回一個記憶體鏡像類型的對象
next(iterator[, default])  類似于iterator.next()
object()  基類
property([fget[, fset[, fdel[, doc]]]])  屬性通路的包裝類,設定後可以通過c.x=value等來通路setter和getter
reduce(function, iterable[, initializer])  合并操作,從第一個開始是前兩個參數,然後是前兩個的結果與第三個合并進行處理,以此類推
reload(module)  重新加載子產品
setattr(object, name, value) 設定屬性值
repr(object)  将一個對象變幻為可列印的格式
slice()  
staticmethod 聲明靜态方法,是個注解
super(type[, object-or-type])  引用父類
type(object) 傳回該object的類型
vars([object])  傳回對象的變量,若無參數與dict()方法類似
bytearray([source [, encoding [, errors]]])

傳回一個byte數組

1、如果source為整數,則傳回一個長度為source的初始化數組;

2、如果source為字元串,則按照指定的encoding将字元串轉換為位元組序列;

3、如果source為可疊代類型,則元素必須為[0 ,255]中的整數;

4、如果source為與buffer接口一緻的對象,則此對象也可以被用于初始化bytearray.

zip([iterable, ...])  實在是沒有看懂,隻是看到了矩陣的變幻方面

五、IO操作

file(filename [, mode [, bufsize]])

file類型的構造函數,作用為打開一個檔案,如果檔案不存在且mode為寫或追加時,檔案将被建立。添加‘b’到mode參數中,将對檔案以二進制形式操作。添加‘+’到mode參數中,将允許對檔案同時進行讀寫操作

1、參數filename:檔案名稱。

2、參數mode:'r'(讀)、'w'(寫)、'a'(追加)。

3、參數bufsize:如果為0表示不進行緩沖,如果為1表示進行行緩沖,如果是一個大于1的數表示緩沖區的大小 。

input([prompt]) 

擷取使用者輸入

推薦使用raw_input,因為該函數将不會捕獲使用者的錯誤輸入

open(name[, mode[, buffering]]) 

打開檔案

與file有什麼不同?推薦使用open

print 列印函數
raw_input([prompt])  設定輸入,輸入都是作為字元串處理

六、其他

help()--幫助資訊

__import__()--沒太看明白了,看到了那句“Direct use of __import__() is rare”之後就沒心看下去了

apply()、buffer()、coerce()、intern()---這些是過期的内置函數,故不說明

七、後記

内置函數,一般都是因為使用頻率比較頻繁或是是元操作,是以通過内置函數的形式提供出來,通過對python的内置函數分類分析可以看出來:基本的資料操作基本都是一些數學運算(當然除了加減乘除)、邏輯操作、集合操作、基本IO操作,然後就是對于語言自身的反射操作,還有就是字元串操作,也是比較常用的,尤其需要注意的是反射操作。

八、内置函數使用示例

1、abs 絕對值

1 print(abs(-1))
2 print(abs(1))      

執行結果:

1 1
2 1      

2、all 所有的都為真,他才為真

1 print(all([1,2,'1']))
2 print(all([1,2,'1','']))
3 print(all(''))    #如果可疊代對象是空,就傳回True      

執行結果:

1 True
2 False
3 True      

3、any 集合中的元素有一個為真的時候為真, 特别的,若為空串傳回為False

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

執行結果:

1 False
2 True      

4、bin 把十進制轉成二進制

1 print(bin(3))      

執行結果:

1 0b11      

5、bool 布爾值   空,None,0的布爾值為False,其餘都為True

1 print(bool(''))  #空字元串,傳回值None
2 print(bool(None))
3 print(bool(0))      

執行結果:

1 False
2 False
3 False      

6、bytes 把字元串轉成位元組

ps1:

1 name='你好'
2 print(bytes(name,encoding='utf-8'))  #手動把字元串編碼,轉成二進制
3 print(bytes(name,encoding='utf-8').decode('utf-8'))  #需要把字元串進行編碼,再解碼(用什麼編碼,就用什麼解碼)      

執行結果:

1 b'\xe4\xbd\xa0\xe5\xa5\xbd'
2 你好      

ps2:

1 name='你好'
2 print(bytes(name,encoding='gbk'))
3 print(bytes(name,encoding='gbk').decode('gbk'))      

執行結果:

1 b'\xc4\xe3\xba\xc3'
2 你好      

ps3: ascll不能編碼中文,會報錯

1 name='你好'
2 print(bytes(name,encoding='ascii')) #ascii不能編碼中文,會報錯      

執行結果:

1 Traceback (most recent call last):
2   File "D:/python/day7/built-in functions.py", line 33, in <module>
3     print(bytes(name,encoding='ascii')) #ascll不能編碼中文,會報錯
4 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)      

7、ascll 碼對應的編碼

1 print(chr(46))   #ascll 碼對應的編碼      

執行結果:

1 .      

8、dir 顯示函數内置屬性和方法

1 print(dir(dict))  #列印内置屬性和方法      

執行結果:

1 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']      

9、divmod 取商得餘數,用于做分頁顯示功能

1 print(divmod(10,3))    #取商得餘數,用于做分頁顯示      

執行結果:

1 (3, 1)      

10、eval  把字元串中的資料結構給提取出來

1 dic={'name':'alex'}  #字典類型轉成字元串
2 dic_str=str(dic)
3 print(dic_str)
4 
5 d1=eval(dic_str)     #eval:把字元串中的資料結構給提取出來
6 print(d1)      

執行結果:

1 {'name': 'alex'}
2 
3 {'name': 'alex'}      

11、可hash的資料類型即不可變資料類型,不可hash的資料類型即可變資料類型

1 #hash的作用:去網上下載下傳軟體,判斷是否被人修改,通過比對hash值,就知道
 2 print(hash('12sdfdsaf3123123sdfasdfasdfasdfasdfasdfasdfasdfasfasfdasdf'))
 3 print(hash('12sdfdsaf31231asdfasdfsadfsadfasdfasdf23'))
 4 
 5 name='alex'
 6 print(hash(name))
 7 print(hash(name))
 8 
 9 print('--->before',hash(name))
10 name='sb'
11 print('=-=>after',hash(name))      

執行結果:

1 1982976672
2 864959982
3 -2006403263
4 -2006403263
5 --->before -2006403263
6 =-=>after 805524431      

12、help 檢視函數用法的說細資訊

1 print(help(all))   #檢視函數用法的詳細資訊      

執行結果:

1 Help on built-in function all in module builtins:
2 
3 all(iterable, /)
4     Return True if bool(x) is True for all values x in the iterable.
5     
6     If the iterable is empty, return True.
7 
8 None      

13、bin、hex、oct  進制轉換

1 print(bin(10))   #10進制->2進制
2 print(hex(12))   #10進制->16進制
3 print(oct(12))   #10進制->8進制      

執行結果:

1 0b1010     #10進制->2進制      
2 0xc        #10進制->16進制      
3 0o14       #10進制->8進制      

14、isinstance判斷類型

1 print(isinstance(1,int))       #判斷是不是int類型
2 print(isinstance('abc',str))   #判斷字元串
3 print(isinstance([],list))     #判斷清單
4 print(isinstance({},dict))     #判斷字典
5 print(isinstance({1,2},set))   #判斷集合      

執行結果:

1 True
2 True
3 True
4 True
5 True      

15、globals 全局變量 

ps1:

1 name='哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陳'
2 print(globals())   #全局變量      

執行結果:

1 {'__doc__': None, '__name__': '__main__', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x01625C30>, '__cached__': None, 'name': '哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陳', '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__file__': 'D:/python/day7/built-in functions.py'}      

ps2:  __file__  直接列印檔案名

1 name='哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陳'
2 print(__file__)    #直接列印檔案名      

執行結果:

1 D:/python/day7/built-in functions.py      

ps3:   globals 列印全局變量,locals 列印上一層的變量

1 def test():
2     age='1111111111111111111111111111111111111111111111111111111111111'
3     print(globals())   #列印全局變量
4     print(locals())    #列印上一層的變量
5 
6 test()      

執行結果:

1 {'__builtins__': <module 'builtins' (built-in)>, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x01CD5C30>, '__file__': 'D:/python/day7/built-in functions.py', 'test': <function test at 0x01DE2F60>, '__package__': None, '__cached__': None, '__name__': '__main__', '__spec__': None, '__doc__': None}
2 {'age': '1111111111111111111111111111111111111111111111111111111111111'}      

16、max 最大值 和 min最小值

ps1:

1 l=[1,3,100,-1,2]
2 print(max(l))
3 print(min(l))      

執行結果:

1 100  #最大值
2 -1     #最小值      

ps2: max 進階用法

說明:

1、max函數處理的是可疊代對象,相當于一個for循環取出每個元素進行比較

注意:不同類型之間不能進行比較

2、每個元素間進行比較,是從每個元素的第一位置依次比較,如果這一個位置分出大小,後

面的都不需要比較了,直接得出這倆元素的大小。

1 age_dic={'alex_age':18,'wupei_age':20,'zsc_age':100,'lhf_age':30}
2 print(max(age_dic.values()))   #取出最大年齡
3 print(max(age_dic))            #預設比較的是字典的key      

執行結果:

1 100
2 zsc_age      

ps3:  取出年齡最大的key和values

1 age_dic={'alex_age':18,'wupei_age':20,'zsc_age':100,'lhf_age':30}
2 for item in zip(age_dic.values(),age_dic.keys()):  #[(18,'alex_age')  (20,'wupeiqi_age') () () ()]
3     print(item)
4 
5 #取出年齡最大的key和values
6 print('=======>',list(max(zip(age_dic.values(),age_dic.keys()))))  #max和zip聯合使用      

執行結果:

1 (100, 'zsc_age')
2 (30, 'lhf_age')
3 (18, 'alex_age')
4 (20, 'wupei_age')
5 
6 
7 =======> [100, 'zsc_age']  #取出年齡最大的key和values      

ps4:

1 l=[
 2     (5,'e'),
 3     (1,'b'),
 4     (3,'a'),
 5     (4,'d'),
 6 ]
 7 l1=['a10','b12','c10',100]   #不同類型之間不能進行比較
 8 l1=['a10','a2','a10']        #不同類型之間不能進行比較
 9 print(list(max(l)))
10 
11 print('--->',list(max(l1)))      

執行結果:

1 [5, 'e']
2 ---> ['a', '2']      

17、zip  将對象逐一配對

ps1:

1 print(list(zip(('a','n','c'),(1,2,3))))
2 print(list(zip(('a','n','c'),(1,2,3,4))))
3 print(list(zip(('a','n','c','d'),(1,2,3))))      

執行結果:

1 [('a', 1), ('n', 2), ('c', 3)]
2 [('a', 1), ('n', 2), ('c', 3)]
3 [('a', 1), ('n', 2), ('c', 3)]      

ps2:

1 p={'name':'alex','age':18,'gender':'none'}
2 print(list(zip(p.keys(),p.values())))
3 print(list(p.keys()))    #取keys
4 print(list(p.values()))  #values
5 
6 print(list(zip(['a','b'],'12345')))   #清單,隻要是序列就可以列印出來      

執行結果:

1 [('age', 18), ('name', 'alex'), ('gender', 'none')]
2 ['age', 'name', 'gender']
3 [18, 'alex', 'none']
4 [('a', '1'), ('b', '2')]      

ps3:

max總結:

1 l=[1,3,100,-1,2]
 2 print(max(l))    #比較出最大值
 3 
 4 
 5 dic={'age1':18,'age2':10}
 6 print(max(dic))           #比較的是key
 7 
 8 
 9 print(max(dic.values()))  #比較的是key,但是不知道是那個key對應的值
10 
11 
12 print(max(zip(dic.values(),dic.keys())))   #結合zip使用      

執行結果:

1 100    #比較大小,得出最大值   
2 
3 age2   #比較的是key
4 
5 18     #比較的是key,但是不知道是那個key對應的值
6 
7 (18, 'age1')   #結合zip拿用      

ps4:

1 people=[
 2     {'name':'alex','age':1000},
 3     {'name':'wupei','age':10000},
 4     {'name':'yuanhao','age':9000},
 5     {'name':'linhaifeng','age':18},
 6 ]
 7 # max(people,key=lambda dic:dic['age'])
 8 print('周紹陳取出來沒有',max(people,key=lambda dic:dic['age']))    #提取年齡中的values,再進行比較
 9 
10 #上面題分解步驟,先取出ret的值,再給max進行比較
11 people=[
12     {'name':'alex','age':1000},
13     {'name':'wupei','age':10000},
14     {'name':'yuanhao','age':9000},
15     {'name':'linhaifeng','age':18},
16 ]
17 
18 ret=[]
19 for item in people:
20     ret.append(item['age'])
21 print(ret)
22 max(ret)      

執行結果:

1 #提取年齡中的values,再進行比較大小,得出age最大的
2 
3 周紹陳取出來沒有 {'name': 'wupei', 'age': 10000}
4 
5 
6 #上面題分解步驟,先取出ret的值,再給max進行比較,得出的值:
7 
8 [1000, 10000, 9000, 18]      

ps5:

chr : 傳回一個字元串,其ASCII碼是一個整型.比如chr(97)傳回字元串'a'。參數i的範圍在0-             255之間。

ord: 參數是一個ascii字元,傳回值是對應的十進制整數

pow: 幾的幾次方

1 print(chr(97))     #ascll碼應對的編碼
2 
3 print(ord('a'))    #ascll碼應對的數字
4 
5 print(pow(3,3))    #3**3   幾的幾次方,相當于3的3次方
6 
7 print(pow(3,3,2))  #3**3%2    3的3次方,取餘      

執行結果:

1 a       #ascll碼應對的編碼
2 
3 97     #ascll碼應對的數字
4 
5 27     #3**3   幾的幾次方,相當于3的3次方
6  
7 1       #3**3%2    3的3次方,取餘      

18、reversed 反轉

1 l=[1,2,3,4]
2 print(list(reversed(l)))
3 print(l)      

執行結果:

1 [4, 3, 2, 1]   #反轉
2 [1, 2, 3, 4]      

19、round  四舍五入

1 print(round(3.5))   #四舍五入      

執行結果:

1 4      

20、set 集合

1 print(set('hello'))   #集合      

執行結果:

1 {'l', 'e', 'o', 'h'}      

21、slice 切片

1 l='hello'
 2 s1=slice(3,5)    #切片 取3到5的元素
 3 s2=slice(1,4,2)  #切片,指定步長為2
 4 print(l[3:5])
 5 
 6 print(l[s1])   #切片
 7 print(l[s2])
 8 
 9 print(s2.start)  #開始
10 print(s2.stop)   #結束
11 print(s2.step)   步長      

執行結果:

1 lo
 2 
 3 lo
 4 
 5 el
 6 
 7 1
 8 
 9 4
10 
11 2      

22、sorted 排序

ps1:

1 l=[3,2,1,5,7]
2 l1=[3,2,'a',1,5,7]
3 print(sorted(l))    #排序
4 # print(sorted(l1)) #直接運作會報錯,因為排序本質就是在比較大小,不同類型之間不可以比較大小      

執行結果:

1 [1, 2, 3, 5, 7]      

ps2:

1 people=[
2     {'name':'alex','age':1000},
3     {'name':'wupei','age':10000},
4     {'name':'yuanhao','age':9000},
5     {'name':'linhaifeng','age':18},
6 ]
7 print(sorted(people,key=lambda dic:dic['age']))    #按年齡進行排序      

執行結果:

1 [{'age': 18, 'name': 'linhaifeng'}, {'age': 1000, 'name': 'alex'}, {'age': 9000, 'name': 'yuanhao'}, {'age': 10000, 'name': 'wupei'}]      

ps3:

1 name_dic={
 2     'abyuanhao': 11900,
 3     'alex':1200,
 4     'wupei':300,
 5 }
 6 print(sorted(name_dic))   #按key排序
 7 
 8 print(sorted(name_dic,key=lambda key:name_dic[key]))   #取出字典的values
 9 
10 print(sorted(zip(name_dic.values(),name_dic.keys())))   #按價格從低到高排序      

執行結果:

1 ['abyuanhao', 'alex', 'wupei']
2 
3 ['wupei', 'alex', 'abyuanhao']
4 
5 [(300, 'wupei'), (1200, 'alex'), (11900, 'abyuanhao')]      

23、str , type 

    str    轉換成字元型

type  檢視某一個東西的資料類型

ps1:      
1 print(str('1'))             #str  轉換成字元型
2 print(type(str({'a':1})))   #type 檢視資料類型
3 
4 dic_str=str({'a':1})
5 print(type(eval(dic_str)))  #eval 轉換資料類型      

 執行結果:

1 1
2 <class 'str'>
3 <class 'dict'>      

ps2:

int類型加1

1 msg='123'
2 if type(msg) is str:
3     msg=int(msg)
4     res=msg+1
5     print(res)      

執行結果:

1 124      

24、vars 跟一個清單或多個字典

1 def test():
2     msg='撒旦法阿薩德防撒旦浪費艾絲凡阿斯蒂芬'
3     print(locals())    #列印出上一層的值,如果上一層沒有,再往上找
4     print(vars())      #如果沒有參數,跟locals一樣,如果有參數,檢視某一個方法,顯示成字典的方式
5 test()
6 print(vars(int))         

執行結果:

1 {'msg': '撒旦法阿薩德防撒旦浪費艾絲凡阿斯蒂芬'}
2 {'msg': '撒旦法阿薩德防撒旦浪費艾絲凡阿斯蒂芬'}
3 {'denominator': <attribute 'denominator' of 'int' objects>, '__mod__': <slot wrapper '__mod__' of 'int' objects>, '__radd__': <slot wrapper '__radd__' of 'int' objects>, '__floordiv__': <slot wrapper '__floordiv__' of 'int' objects>, '__doc__': "int(x=0) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given.  If x is a number, return x.__int__().  For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base.  The literal can be preceded by '+' or '-' and be surrounded\nby whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4", '__ceil__': <method '__ceil__' of 'int' objects>, '__sizeof__': <method '__sizeof__' of 'int' objects>, '__pos__': <slot wrapper '__pos__' of 'int' objects>, '__gt__': <slot wrapper '__gt__' of 'int' objects>, '__rtruediv__': <slot wrapper '__rtruediv__' of 'int' objects>, '__sub__': <slot wrapper '__sub__' of 'int' objects>, '__rdivmod__': <slot wrapper '__rdivmod__' of 'int' objects>, '__new__': <built-in method __new__ of type object at 0x5D677028>, '__rshift__': <slot wrapper '__rshift__' of 'int' objects>, '__rmod__': <slot wrapper '__rmod__' of 'int' objects>, '__neg__': <slot wrapper '__neg__' of 'int' objects>, '__xor__': <slot wrapper '__xor__' of 'int' objects>, '__rmul__': <slot wrapper '__rmul__' of 'int' objects>, '__repr__': <slot wrapper '__repr__' of 'int' objects>, '__hash__': <slot wrapper '__hash__' of 'int' objects>, 'to_bytes': <method 'to_bytes' of 'int' objects>, 'from_bytes': <method 'from_bytes' of 'int' objects>, 'real': <attribute 'real' of 'int' objects>, '__lt__': <slot wrapper '__lt__' of 'int' objects>, '__invert__': <slot wrapper '__invert__' of 'int' objects>, '__eq__': <slot wrapper '__eq__' of 'int' objects>, '__float__': <slot wrapper '__float__' of 'int' objects>, '__round__': <method '__round__' of 'int' objects>, '__ror__': <slot wrapper '__ror__' of 'int' objects>, '__le__': <slot wrapper '__le__' of 'int' objects>, '__rlshift__': <slot wrapper '__rlshift__' of 'int' objects>, 'bit_length': <method 'bit_length' of 'int' objects>, '__getnewargs__': <method '__getnewargs__' of 'int' objects>, '__index__': <slot wrapper '__index__' of 'int' objects>, '__rsub__': <slot wrapper '__rsub__' of 'int' objects>, '__format__': <method '__format__' of 'int' objects>, '__bool__': <slot wrapper '__bool__' of 'int' objects>, '__or__': <slot wrapper '__or__' of 'int' objects>, '__int__': <slot wrapper '__int__' of 'int' objects>, 'imag': <attribute 'imag' of 'int' objects>, 'conjugate': <method 'conjugate' of 'int' objects>, '__ge__': <slot wrapper '__ge__' of 'int' objects>, '__and__': <slot wrapper '__and__' of 'int' objects>, '__abs__': <slot wrapper '__abs__' of 'int' objects>, '__floor__': <method '__floor__' of 'int' objects>, '__divmod__': <slot wrapper '__divmod__' of 'int' objects>, '__trunc__': <method '__trunc__' of 'int' objects>, '__rrshift__': <slot wrapper '__rrshift__' of 'int' objects>, '__mul__': <slot wrapper '__mul__' of 'int' objects>, '__pow__': <slot wrapper '__pow__' of 'int' objects>, '__str__': <slot wrapper '__str__' of 'int' objects>, '__ne__': <slot wrapper '__ne__' of 'int' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'int' objects>, '__truediv__': <slot wrapper '__truediv__' of 'int' objects>, '__add__': <slot wrapper '__add__' of 'int' objects>, '__rand__': <slot wrapper '__rand__' of 'int' objects>, '__rfloordiv__': <slot wrapper '__rfloordiv__' of 'int' objects>, '__lshift__': <slot wrapper '__lshift__' of 'int' objects>, '__rxor__': <slot wrapper '__rxor__' of 'int' objects>, 'numerator': <attribute 'numerator' of 'int' objects>, '__rpow__': <slot wrapper '__rpow__' of 'int' objects>}      

25、import 子產品

1、先建立一個test.py檔案

寫入内容如下:

1 def say_hi():
2     print('你好啊林師傅')      

2、再調用這個子產品

1 import test     #導入一個子產品,子產品就是一個py檔案
2 test.say_hi()      

執行結果:

1 你好啊林師傅      

26、__import__  :導入一個字元串類型子產品,就要用__import__

1、先建立一個test.py檔案

寫入内容如下:

1 def say_hi():
2     print('你好啊林師傅')      

2、再調用這個子產品

1 module_name='test'
2 m=__import__(module_name)   #有字元串的子產品
3 m.say_hi()      

執行結果:

1 你好啊林師傅      

轉載于:https://www.cnblogs.com/niejinmei/p/6761582.html