Python常用的內置函數


一  反射相關

  1 hasattr   根據字符串的形式 , 去判斷對象中是否有成員

hasattr(object,name)
判斷對象object是否包含名為name的特性(hasattr是通過調用getattr(object,name))是否拋出異常來實現的。
參數object:對象
參數name:特性名稱
>>> hasattr(list, 'append')
True
>>> hasattr(list, 'add')
False
View Code

  2 getattr  根據字符串的形式,去對象中找成員.   第一個參數是(模塊或對象或類),  第二個參數是(用戶輸入或值)getattr(object, name [, defalut])獲取對象object名為name的特性,如果object不包含名為name的特性,將會拋出AttributeError異常;如果不包含名為name的特性且提供default參數,將返回default。

參數object:對象
參數name:對象的特性名
參數default:缺省返回值
>>> class test():
...  name="ming"
...   def run(self):
...     return "Hello World"
...
>>> t=test()
>>> getattr(t, "name") #獲取name屬性,存在就打印出來。
'ming'
>>> getattr(t, "run") #獲取run方法,存在就打印出方法的內存地址。
<bound method test.run of <__main__.test instance at 0x0269C878>>
>>> ret = getattr(t, "run")() #獲取run方法,后面加括號可以將這個方法運行。
>>> print(ret)
'Hello World' >>> getattr(t, "age") #獲取一個不存在的屬性。 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: test instance has no attribute 'age' >>> getattr(t, "age","18") #若屬性不存在,返回一個默認值。 '18' >>>

  3 setattr   根據字符串的形式 , 動態的設置一個成員(在內存中)  (三個參數, 第一個參數是要設置的變量, 第三個變量是要設置的值)

給對象的屬性賦值,若屬性不存在,先創建再賦值
>>> class test():
...     name="ming"
...     def run(self):
...             return "Hello World"
...
>>> t=test()
>>> hasattr(t, "age")   #判斷屬性是否存在
False
>>> setattr(t, "age", "18")   #為屬相賦值,並沒有返回值
>>> hasattr(t, "age")    #屬性存在了
True
View Code

  4 delattr     

綜合使用

>>> class test():
       name="ming"
       def run(self):
             return "Hello World">>> t=test()
>>> getattr(t, "age")    #age屬性不存在
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'


>>> if getattr(t ,"age") is none: #當獲取到這個age值為空時,需要給這個age重新賦值
    setattr(t,"age","18")
'True'

>>>getattr(t,"age")
'18'

 

二 基礎數據類型相關

  1 bool     

  2 int

  3 float

  4 complex   復數   

complex(5,6)    
(5+6j)

  5 bin  整型轉換為二進制

  6 oct  整型轉換為八進制

  7 hex  整型轉換為十六進制

  8 abs  求絕對值

  9 divmod  (除,余數)

  10 round     (值,小數后幾位)

 ret =  round(4.563111347,3)    
 print(ret)
 4.563

  11 pow  冪運算

ret = pow(2,3)
print(ret)

8

  12 sum  

  13 max

  14 min

  15 list 

  16 tuple

  17 reversed 

a = [0, 1, 2, 3, 4, 5, 6]
b = reversed(a)
print(b)
>>> <list_reverseiterator object at 0x0000000001E7F198>
print(list(b))
>>> [6, 5, 4, 3, 2, 1, 0]
print(list(b)) 
>>> []

因此,reversed()返回的是一個迭代器對象,只能進行一次循環遍歷並只能顯示一次所包含的值!

      18  slice   和切片有關

  19 str

  20 format     格式化輸出

  21 bytes

  22 bytearry

x = bytearray(5)
print(x)

>>> bytearray(b'\x00\x00\x00\x00\x00')

  23 memoryview

memory 內存,view 查看。那么memoryview()函數返回給定參數的內存查看對象。內存查看對象指對支持緩沖區協議的數據進行包裝,
在不需要復制對象基礎上允許Python代碼訪問。

s = memoryview(bytearray('abcdefgh','utf-8'))
print(s[1])
>>> 98
print(s[-1])
>>> 104
print(s[1:4])
>>> <memory at 0x00000000021E0408>

  24 ord  函數主要用來返回對應字符的ascii碼

  25 chr  主要用來表示ascii碼對應的字符,輸入可以是數字,可以是十進制,也可以是十六進制

  26 ascill

  27 repr

repr() 函數將對象轉化為供解釋器讀取的形式且返回一個對象的string格式
s = 'RUNOOB'
print(repr(s))
>>> 'RUNOOB'
dict = {'runoob': 'runoob.com', 'google': 'google.com'} 
print(repr(dict)) 
>>> {'runoob': 'runoob.com', 'google': 'google.com'}

  28 dict

  29 set

  30 frozenset  不可變集合

  31 len

  32 sorted

a = [1,3,5,-2,-4,-6]
b = sorted(a,key=abs)
c = sorted(a)

print(a)
>>> [1, 3, 5, -2, -4, -6]
print(b)
>>> [1, -2, 3, -4, 5, -6]
print(c)
>>> [-6, -4, -2, 1, 3, 5]

  33 enumerate   

 a = enumerate()  返回一個元祖  a[0]序列號,a[1]數據

  34 all

接受一個迭代器,如果迭代器的所有元素都為真,那么返回True,否則返回False

tmp_1 = ['python',123]
all(tmp_1)
>>> True
tmp_2 = []
all(tmp_2)
>>> True
tmp_3 = [0]
all(tmp_3)
>>> False

  35 any

接受一個迭代器,如果迭代器里有一個元素為真,那么返回True,否則返回False
a = []
ret = any(a)
print(ret)
>>> False

b = [1]
ret1 = any(b)
print(ret1)
>>> True

  36 zip

list1 = [1, 2, 3, 4]
list2 = ["a", "b", "c"]
s = zip(list1, list2)
print(list(s))

>>> [(1, 'a'), (2, 'b'), (3, 'c')]

  37 filter

filter()函數接收一個函數 f 和一個list,這個函數 f 的作用是對每個元素進行判斷,返回 True或 False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list

def is_odd(x):
    return x % 2 == 1
然后,利用filter()過濾掉偶數:

list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))

  38 map

map函數應用於每一個可迭代的項,返回的是一個結果list。如果有其他的可迭代參數傳進來,map函數則會把每一個參數都以相應的處理函數進行迭代處理。map()函數接收兩個參數,一個是函數,一個是序列,map將傳入的函數依次作用到序列的每個元素,並把結果作為新的list返回。

L = [1,2,3,4,] 
def pow2(x): 
  return x*x list(map(pow2,L)) >>> [1, 4, 9, 16]

三 作用域相關

  1 locals   獲取執行本方法所在命名空間內的局部變量的字典

  2 globals  獲取全局變量的字典

四 面向對象相關

  1 type  元類,類的最高層

  2 object

  3 classmethod    類方法,用來修改類變量的

  4 staticmethod    靜態方法,用來處理一些和操作類無關的事

  5 property    可以像調用一個變量一樣調用一個方法

 class Pager:
     def __init__(self,page):
         self.page = page
       self.page_num = 12

    @property
     def start(self):
         ret = (self.page - 1) * self.page_num
         return ret
     @property
     def end(self):
         ret = self.page * self.page_num
        return ret

 p = Pager(5)
 # print(p.start())
 # print(p.end())
 print(p.start)
 print(p.end)

  6  vars 

class My():
    'Test'
    def __init__(self,name):
        self.name=name

    def test(self):
        print self.name

vars(My)#返回一個字典對象,他的功能其實和  My.__dict__  很像 

  7 super  在多繼承中,可以保證頂層父類只被調用一次 ,用 _ _mro_ _ 查看多繼承規律時,遵循深度優先原則

  8 issubclass

檢查第一個參數是否是第二個參數的子子孫孫類    

返回  :   是一個布爾值

class Base(object):
    pass

class Foo(Base):
    pass

class Bar(Foo):
    pass

print(issubclass(Bar,Base))  # 檢查第一個參數是否是第二個參數的子子孫孫類

  9 isinstance

檢查第一個參數(對象) 是否是第二個參數(類及父類)的實例.

返回值:  布爾型

class Base(object):
    pass

class Foo(Base):
    pass

obj = Foo()

print(isinstance(obj,Foo))
print(isinstance(obj,Base))

判斷一個數據是什么數據類型 a
= "python" ret = isinstance(a,str) print(a)

五 迭代/生成器相關

  1 next

  2 iter  

  3 range

range 是一個生成器,他只用來存儲數據的生成方式,而不直接存儲數據
# 列表解析
sum([i for i in range(100000000)])# 內存占用大,機器容易卡死
 
# 生成器表達式
sum(i for i in range(100000000))# 幾乎不占內存

六 其他

  字符串類型代碼執行相關  

  1 eval

eval() 將字符串類型的代碼執行並返回結果

print(eval('1+2+3+4'))

還可以用來操作文件,將文件里面的內容轉化為字典,方便調用

 

 
        

  2 exec

exec()將自字符串類型的代碼執行

print(exec("aa = 11 + 22"))
>>> None
print("value is:", aa)
>>> 33

 exec("print('hello,world')")

 >>> hello,world

  3 compile

參數說明:

    1> 參數source:字符串或者AST(Abstract Syntax Trees)對象。即需要動態執行的代碼段。       2>參數 filename:代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認的值。當傳入了source參數時,filename參數傳入空字符即可。       3> 參數model:指定編譯代碼的種類,可以指定為 ‘exec’,’eval’,’single’。當source中包含流程語句時,model應指定為‘exec’;當source中只包含一個簡單的求值表      達式,model應指定為‘eval’;當source中包含了交互式命令語句,model應指定為'single'

 

  輸入/輸出相關

  4 input

  5 print

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
      print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
      file: 默認是輸出到屏幕,如果設置為文件句柄,輸出到文件
      sep: 打印多個值之間的分隔符,默認為空格
      end: 每一次打印的結尾,默認為換行符
      flush: 立即把內容輸出到流文件,不作緩存
    """

    file() 和文件有關的關鍵字

    f = open('tmp_file','w')
    print(123,456,sep=',',file = f,flush=True)
    打印進度條             
import time       for i in range(0,101,2):       time.sleep(0.1)       char_num = i//2 #打印多少個'*'       per_str = '\r%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num)       print(per_str,end='', flush=True)       #小越越 : \r 可以把光標移動到行首但不換行

  內存相關

  6 id

  7 hash

  文件操作相關

  8 open

共有六種操作文件的方分別為:  r、w、a、r+、w+、a+  ,每一種都可以用二進制文件來操作:rb、wb、ab、rb+、wb+、ab+,也可以指定編碼格式

  模塊相關

  9 __import__

  幫助相關

  10 help

  調用相關

  11 callable      檢測一個對象能否被調用

  查看內置屬性和方法

  12 dir

dir(list)
dir(a)
dir(123)

 

內置函數官方文檔        https://docs.python.org/3/library/functions.html#object

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM