python內置函數和魔法函數


內置方法:Python中聲明每一個類系統都會加上一些默認內置方法,提供給系統調用該類的對象時使用。比如需要實例化一個對象時,需要調用該類的init方法;使用print去打印一個類時,其實調用的是str方法等等。

  • init(self, …):初始化對象class,在創建新對象時調用。在方法里,可以初始化該對象的屬性,否則調用其他時可能出“現has no attribute”錯誤;
  • del(self):釋放對象,在對象被虛擬機刪除之前調用;
  • new(cls,*args,**kwd):實例的生成操作,相比init在對象實例化調用做初始化,new方法運行在實例化階段,修改某些實例化過程;
  • str(self):在使用print語句時被調用,將對象的屬性值拼接成字符串返回;
  • getitem(self, key):獲取序列的索引key對應的值,需要使用[]操作符的類需要覆蓋的,等價於seq[key];
  • setitem(self, key, value):類似geitem,需要seq[key]=value操作的類需要實現該方法;
  • len(self):在調用內聯函數len()時被調用;
  • getattr(s, name): 獲取屬性的值;
  • setattr(s, name, value):設置屬性的值;
  • delattr(s, name): 刪除name屬性;
  • getattribute():getattribute()功能與getattr()類似,無條件被調用,通過實例訪問屬性。如果class中定義了getattr(),則getattr()不會被調用(除非顯示調用或引發AttributeError異常);
  • gt(self, other):判斷self對象是否大於other對象;
  • lt(self, other):判斷self對象是否小於other對象;
  • ge(slef, other):判斷self對象是否大於或者等於other對象;
  • le(self, other): 判斷self對象是否小於或者等於other對象;
  • eq(self, other):判斷self對象是否等於other對象;
  • call(self, *args): 把實例對象作為函數調用,在一個對象后面加上(),虛擬機就會調用該call方法。

內置變量:

  • name:標識模塊的名字的一個系統變量。假如當前模塊是主模塊(也就是調用其他模塊的模塊),那么此模塊名字就是”main“,通過if判斷這樣就可以執行“main”后面的主函數內容;假如此模塊是被import的,則此模塊名字為文件名字(不加后面的.py),通過if判斷這樣就會跳過“main”后面的內容;
  • file:用來獲得模塊所在的路徑的,這可能得到的是一個相對路徑;
  • package:當前文件為None,導入其他文件,指定文件所在包用 . 分割;
  • doc:文件注釋

python英文官方文檔詳細說明:點擊查看

魔法函數

  • Python進階:實例講解Python中的魔法函數(Magic Methods)

  • 定制類和魔法方法

  • python中以雙下划線開始和結束的函數(不可自己定義)為魔法函數
  • 調用類實例化的對象的方法時自動調用魔法函數(感覺不需要顯示調用的函數都叫)
  • 在自己定義的類中,可以實現之前的內置函數,比如下面比較元素sorted時用It函數(lt(self, other):判斷self對象是否小於other對象;)
class MyVector(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other_instance):
        re_vector = MyVector(self.x+other_instance.x, self.y+other_instance.y)
        return re_vector

    def __str__(self):
        return"x:{x}, y:{y}".format(x=self.x, y=self.y)


first_vec = MyVector(1,2)
second_vec = MyVector(2,3)
print(first_vec+second_vec)

操作符重載:通過定義類的一些約定的以"__"開頭並結尾的函數,可以到達重載一些特定操作的目的

__str__ / __unicode__       
當print一個對象實例時,實際是print該實例 .str()函數的返回值:

class A:
    def __str__(self):
        return "A"
    def __unicode__(self):
        return "uA"

魔法函數有什么作用?

魔法函數可以為你寫的類增加一些額外功能,方便使用者理解。舉個簡單的例子,我們定義一個“人”的類People,當中有屬性姓名name、年齡age。讓你需要利用sorted函數對一個People的數組進行排序,排序規則是按照name和age同時排序,即name不同時比較name,相同時比較age。由於People類本身不具有比較功能,所以需要自定義,你可以這么定義People類:

class People(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        return

    def __str__(self):
        return self.name + ":" + str(self.age)

    def __lt__(self, other):
        return self.name < other.name if self.name != other.name else self.age < other.age




if __name__=="__main__":

    print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))
  • 上個例子中的__lt__函數即less than函數,即當比較兩個People實例時自動調用。

Python中有哪些魔法函數?

Python中每個魔法函數都對應了一個Python內置函數或操作,比如__str__對應str函數,__lt__對應小於號<等。Python中的魔法函數可以大概分為以下幾類:

類的構造、刪除:

object.__new__(self, ...) object.__init__(self, ...) object.__del__(self) 

二元操作符:

+ object.__add__(self, other) - object.__sub__(self, other) * object.__mul__(self, other) // object.__floordiv__(self, other) / object.__div__(self, other) % object.__mod__(self, other) ** object.__pow__(self, other[, modulo]) << object.__lshift__(self, other) >> object.__rshift__(self, other) & object.__and__(self, other) ^ object.__xor__(self, other) | object.__or__(self, other) 

擴展二元操作符:

+= object.__iadd__(self, other) -= object.__isub__(self, other) *= object.__imul__(self, other) /= object.__idiv__(self, other) //= object.__ifloordiv__(self, other) %= object.__imod__(self, other) **= object.__ipow__(self, other[, modulo]) <<= object.__ilshift__(self, other) >>= object.__irshift__(self, other) &= object.__iand__(self, other) ^= object.__ixor__(self, other) |= object.__ior__(self, other) 

一元操作符:

- object.__neg__(self) + object.__pos__(self) abs() object.__abs__(self) ~ object.__invert__(self) complex() object.__complex__(self) int() object.__int__(self) long() object.__long__(self) float() object.__float__(self) oct() object.__oct__(self) hex() object.__hex__(self) round() object.__round__(self, n) floor() object__floor__(self) ceil() object.__ceil__(self) trunc() object.__trunc__(self) 

比較函數:

< object.__lt__(self, other) <= object.__le__(self, other) == object.__eq__(self, other) != object.__ne__(self, other) >= object.__ge__(self, other) > object.__gt__(self, other) 

類的表示、輸出:

str() object.__str__(self) repr() object.__repr__(self) len() object.__len__(self) hash() object.__hash__(self) bool() object.__nonzero__(self) dir() object.__dir__(self) sys.getsizeof() object.__sizeof__(self) 

類容器:

len() object.__len__(self) self[key] object.__getitem__(self, key) self[key] = value object.__setitem__(self, key, value) del[key] object.__delitem__(self, key) iter() object.__iter__(self) reversed() object.__reversed__(self) in操作 object.__contains__(self, item) 字典key不存在時 object.__missing__(self, key)


免責聲明!

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



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