Python常用內建函式總結

2021-07-26 13:18:11 字數 4387 閱讀 4863

內建方法

說明__init__(self,...)

初始化物件,在建立新物件時呼叫

__del__(self)

釋放物件,在物件被刪除之前呼叫

__new__(cls,*args,**kwd)

例項的生成操作

__str__(self)

在使用print語句時被呼叫

__getitem__(self,key)

獲取序列的索引key對應的值,等價於seq[key]

__len__(self)

在呼叫內聯函式len()時被呼叫

__cmp__(stc,dst)

比較兩個物件src和dst

__getattr__(s,name)

獲取屬性的值

__setattr__(s,name,value)

設定屬性的值

__delattr__(s,name)

刪除name屬性

__getattribute__()

__getattribute__()功能與__getattr__()類似

__gt__(self,other)

判斷self物件是否大於other物件

__lt__(slef,other)

判斷self物件是否小於other物件

__ge__(slef,other)

判斷self物件是否大於或者等於other物件

__le__(slef,other)

判斷self物件是否小於或者等於other物件

__eq__(slef,other)

判斷self物件是否等於other物件

__call__(self,*args)

把例項物件作為函式呼叫

__init__():

__init__方法在類的乙個物件被建立時,馬上執行。這個方法可以用來對你的物件做一些你希望的初始化。注意,這個名稱的開始和結尾都是雙下劃線。

**例子:

#!/usr/bin/python

# filename: class_init.py

class person:

def __init__(self, name):

self.name = name

def sayhi(self):

print 'hello, my name is', self.name

p = person('swaroop')

p.sayhi()

輸出:hello, my name is swaroop

說明:__init__方法定義為取乙個引數name(以及普通的引數self)。在這個__init__裡,我們只是建立乙個新的域,也稱為name。注意它們是兩個不同的變數,儘管它們有相同的名字。點號使我們能夠區分它們。最重要的是,我們沒有專門呼叫__init__方法,只是在建立乙個類的新例項的時候,把引數包括在圓括號內跟在類名後面,從而傳遞給__init__方法。這是這種方法的重要之處。現在,我們能夠在我們的方法中使用self.name域。這在sayhi方法中得到了驗證。

__new__():

__new__()在__init__()之前被呼叫,用於生成例項物件.利用這個方法和類屬性的特性可以實現設計模式中的單例模式.單例模式是指建立唯一物件嗎,單例模式設計的類只能例項化乙個物件.

#!/usr/bin/python

# -*- coding: utf-8 -*-

class singleton(object):

__instance = none                       # 定義例項

def __init__(self):

pass

def __new__(cls, *args, **kwd):         # 在__init__之前呼叫

if singleton.__instance is none:    # 生成唯一例項

singleton.__instance = object.__new__(cls, *args, **kwd)

return singleton.__instance

__getattr__()、__setattr__()和__getattribute__():

當讀取物件的某個屬性時,python會自動呼叫__getattr__()方法.例如,fruit.color將轉換為fruit.__getattr__(color).當使用賦值語句對屬性進行設定時,python會自動呼叫__setattr__()方法.__getattribute__()的功能與__getattr__()類似,用於獲取屬性的值.但是__getattribute__()能提供更好的控制,**更健壯.注意,python中並不存在__setattribute__()方法.

**例子:

#!/usr/bin/python

# -*- coding: utf-8 -*-

class fruit(object):

def __init__(self, color = "red", price = 0):

self.__color = color

self.__price = price

def __getattribute__(self, name):               # 獲取屬性的方法

return object.__getattribute__(self, name)

def __setattr__(self, name, value):

self.__dict__[name] = value

if __name__ == "__main__":

fruit = fruit("blue", 10)

print fruit.__dict__.get("_fruit__color")       # 獲取color屬性

fruit.__dict__["_fruit__price"] = 5

print fruit.__dict__.get("_fruit__price")       # 獲取price屬性

__getitem__():

如果類把某個屬性定義為序列,可以使用__getitem__()輸出序列屬性中的某個元素.假設水果店中銷售多鐘水果,可以通過__getitem__()方法獲取水果店中的沒種水果

**例子:

#!/usr/bin/python

# -*- coding: utf-8 -*-

class fruitshop:

def __getitem__(self, i):      # 獲取水果店的水果

return self.fruits[i]      

__str__():

__str__()用於表示物件代表的含義,返回乙個字串.實現了__str__()方法後,可以直接使用print語句輸出物件,也可以通過函式str()觸發__str__()的執行.這樣就把物件和字串關聯起來,便於某些程式的實現,可以用這個字串來表示某個類

**例子:

#!/usr/bin/python

# -*- coding: utf-8 -*-

class fruit:      

'''fruit類'''               #為fruit類定義了文件字串

def __str__(self):          # 定義物件的字串表示

return self.__doc__

if __name__ == "__main__":

fruit = fruit()

print str(fruit)            # 呼叫內建函式str()出發__str__()方法,輸出結果為:fruit類

print fruit                 #直接輸出物件fruit,返回__str__()方法的值,輸出結果為:fruit類

__call__():

在類中實現__call__()方法,可以在物件建立時直接返回__call__()的內容.使用該方法可以模擬靜態方法

**例子:

#!/usr/bin/python

# -*- coding: utf-8 -*-

class fruit:

class growth:        # 內部類

def __call__(self):

print "grow ..."

grow = growth()      # 呼叫growth(),此時將類growth作為函式返回,即為外部類fruit定義方法grow(),grow()將執行__call__()內的**

if __name__ == '__main__':

fruit = fruit()

fruit.grow()         # 輸出結果:grow ...

fruit.grow()         # 輸出結果:grow ...

**  

python中常用內建函式用法總結

強制型別轉換 int float str list tuple set dict 總結,這幾種型別轉換函式得用法基本一致,基本就是int 要轉換得資料 返回值型別為對應得資料型別 max 求多個引數的最大值,或可迭代物件中的最大元素 min 最小值 sum 求和,可迭代物件元素求和 pow 求冪,p...

Python常用內建函式

1 絕對值 abs 1 2 最大最小值 max 1,2,3 min 1,2,3 3 序列長度 len abc len 1,2,3 len 1,2,3 4 取模 divmod 5,2 2,1 5 乘方 pow 2,3,4 2 3 4 6 浮點數 round 1 1 函式是否可呼叫 callable f...

python常用內建函式

locals 當前作用域內所有變數 globals 全域性所有變數 next 迭代器 iter 可迭代物件 range dir 檢視乙個物件擁有的屬性 callable 括號內為可呼叫函式時返回true help open writable readable hash 括號內必須為乙個可雜湊型別 e...