国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Python常用內(nèi)置函數(shù)總結(jié)

2019-11-14 13:07:54
字體:
供稿:網(wǎng)友
 內(nèi)置方法 說明
 __init__(self,...) 初始化對象,在創(chuàng)建新對象時調(diào)用
 __del__(self) 釋放對象,在對象被刪除之前調(diào)用
 __new__(cls,*args,**kwd) 實例的生成操作
 __str__(self) 在使用PRint語句時被調(diào)用
 __getitem__(self,key) 獲取序列的索引key對應(yīng)的值,等價于seq[key]
 __len__(self) 在調(diào)用內(nèi)聯(lián)函數(shù)len()時被調(diào)用
 __cmp__(stc,dst) 比較兩個對象src和dst
 __getattr__(s,name) 獲取屬性的值
 __setattr__(s,name,value) 設(shè)置屬性的值
 __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) 把實例對象作為函數(shù)調(diào)用

__init__():__init__方法在類的一個對象被建立時,馬上運行。這個方法可以用來對你的對象做一些你希望的初始化。注意,這個名稱的開始和結(jié)尾都是雙下劃線。代碼例子:

#!/usr/bin/python# Filename: class_init.pyclass 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__方法定義為取一個參數(shù)name(以及普通的參數(shù)self)。在這個__init__里,我們只是創(chuàng)建一個新的域,也稱為name。注意它們是兩個不同的變量,盡管它們有相同的名字。點號使我們能夠區(qū)分它們。最重要的是,我們沒有專門調(diào)用__init__方法,只是在創(chuàng)建一個類的新實例的時候,把參數(shù)包括在圓括號內(nèi)跟在類名后面,從而傳遞給__init__方法。這是這種方法的重要之處。現(xiàn)在,我們能夠在我們的方法中使用self.name域。這在sayHi方法中得到了驗證。

__new__():__new__()在__init__()之前被調(diào)用,用于生成實例對象.利用這個方法和類屬性的特性可以實現(xiàn)設(shè)計模式中的單例模式.單例模式是指創(chuàng)建唯一對象嗎,單例模式設(shè)計的類只能實例化一個對象.

#!/usr/bin/python# -*- coding: UTF-8 -*-

class Singleton(object):    __instance = None                       # 定義實例

    def __init__(self):        pass

    def __new__(cls, *args, **kwd):         # 在__init__之前調(diào)用        if Singleton.__instance is None:    # 生成唯一實例            Singleton.__instance = object.__new__(cls, *args, **kwd)        return Singleton.__instance

   

__getattr__()、__setattr__()和__getattribute__():當讀取對象的某個屬性時,python會自動調(diào)用__getattr__()方法.例如,fruit.color將轉(zhuǎn)換為fruit.__getattr__(color).當使用賦值語句對屬性進行設(shè)置時,python會自動調(diào)用__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__()輸出序列屬性中的某個元素.假設(shè)水果店中銷售多鐘水果,可以通過__getitem__()方法獲取水果店中的沒種水果代碼例子:

#!/usr/bin/python# -*- coding: UTF-8 -*-

class FruitShop:     def __getitem__(self, i):      # 獲取水果店的水果         return self.fruits[i]      

if __name__ == "__main__":    shop = FruitShop()    shop.fruits = ["apple", "banana"]    print shop[1]    for item in shop:               # 輸出水果店的水果        print item,

輸出為:bananaapple banana

   

__str__():__str__()用于表示對象代表的含義,返回一個字符串.實現(xiàn)了__str__()方法后,可以直接使用print語句輸出對象,也可以通過函數(shù)str()觸發(fā)__str__()的執(zhí)行.這樣就把對象和字符串關(guān)聯(lián)起來,便于某些程序的實現(xiàn),可以用這個字符串來表示某個類代碼例子:

#!/usr/bin/python# -*- coding: UTF-8 -*-

class Fruit:          '''Fruit類'''               #為Fruit類定義了文檔字符串    def __str__(self):          # 定義對象的字符串表示        return self.__doc__

if __name__ == "__main__":    fruit = Fruit()    print str(fruit)            # 調(diào)用內(nèi)置函數(shù)str()出發(fā)__str__()方法,輸出結(jié)果為:Fruit類    print fruit                 #直接輸出對象fruit,返回__str__()方法的值,輸出結(jié)果為:Fruit類

   

__call__():在類中實現(xiàn)__call__()方法,可以在對象創(chuàng)建時直接返回__call__()的內(nèi)容.使用該方法可以模擬靜態(tài)方法代碼例子:

#!/usr/bin/python# -*- coding: UTF-8 -*-

class Fruit:    class Growth:        # 內(nèi)部類        def __call__(self):            print "grow ..."

    grow = Growth()      # 調(diào)用Growth(),此時將類Growth作為函數(shù)返回,即為外部類Fruit定義方法grow(),grow()將執(zhí)行__call__()內(nèi)的代碼if __name__ == '__main__':    fruit = Fruit()    fruit.grow()         # 輸出結(jié)果:grow ...    Fruit.grow()         # 輸出結(jié)果:grow ...

  

轉(zhuǎn)自 http://xukaizijian.blog.163.com/blog/static/170433119201111894228877/ 

https://docs.python.org/3/library/functions.html#abs


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 乌兰察布市| 清苑县| 西贡区| 呼和浩特市| 哈巴河县| 扎赉特旗| 梓潼县| 新安县| 凭祥市| 襄垣县| 永昌县| 连城县| 西林县| 图片| 华蓥市| 克拉玛依市| 和林格尔县| 乳山市| 汪清县| 瓮安县| 个旧市| 青阳县| 边坝县| 闸北区| 简阳市| 江油市| 疏附县| 高邮市| 石河子市| 呼和浩特市| 尖扎县| 嘉祥县| 海宁市| 武陟县| 长乐市| 江西省| 镇江市| 焦作市| 荔浦县| 伊吾县| 广水市|