1. 程式人生 > 其它 >Python高階語法:魔法函式

Python高階語法:魔法函式

介紹的魔法函式有(持續更新): __ init__()、__ str__()、__ new__()、__ unicode__()、 __ call__()、 __ len__()、 __repr__()、__ setattr__()、 __ getattr__()、 __ getattribute__()、 __ delattr__()、__ setitem__()、 __ getitem__()、__ delitem__()、 __ iter__()、__ del__()、 __dir__()、__dict__()、__exit__(),__enter(), __all__()等函式。

1. 前言

1.1 什麼是魔法函式?

魔法函式一覽

所謂魔法函式(Magic Methods),是Python的一種高階語法,允許你在類中自定義函式(函式名格式一般為__xx__),並繫結到類的特殊方法中。比如在類A中自定義__str__()函式,則在呼叫str(A())時,會自動呼叫__str__()函式,並返回相應的結果。在我們平時的使用中,可能經常使用__init__函式(建構函式)和__del__函式(解構函式),其實這也是魔法函式的一種。

  • Python中以雙下劃線(__xx__)開始和結束的函式(不可自己定義)為魔法函式。
  • 呼叫類例項化的物件的方法時自動呼叫魔法函式。
  • 在自己定義的類中,可以實現之前的內建函式。

1.2 魔法函式有什麼作用?

魔法函式可以為你寫的類增加一些額外功能,方便使用者理解。舉個簡單的例子,我們定義一個“人”的類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)])]))

輸出結果:

abc:17	abc:18	abe:12	abe:19

上個例子中的__lt__函式即less than函式,即當比較兩個People例項時自動呼叫。

2. 常見的魔法函式

我們將魔法方法分為:非數學運算和數學運算兩大類。

2.1 非數學運算

2.1.1字串表示

__repr__函式和__str__函式:

初識CV:字串表示:__repr__函式和__str__函式:​zhuanlan.zhihu.com

2.1.2 集合、序列相關

__len__函式、__getitem__函式、__setitem__函式、__delitem__函式和__contains__函式:

初識CV:集合、序列相關:__len__函式、__getitem__函式、__setitem__函式、__delitem__函式和__contains__函式​zhuanlan.zhihu.com

2.1.3 迭代相關

__iter__函式和__next__函式:

初識CV:迭代相關:__iter__函式和__next__函式​zhuanlan.zhihu.com

2.1.4可呼叫

__call__函式:

初識CV:可呼叫:__call__函式​zhuanlan.zhihu.com

2.1.5with上下文管理器

__enter__函式和__exit__函式:

初識CV:with上下文管理器:__enter__函式和__exit__函式​zhuanlan.zhihu.com

2.1.6 數值轉換

__abs__函式、__bool__函式、__int__函式、__float__函式、__hash__函式和__index__函式:

2.1.7 元類相關

__new__函式和__init__函式:

初識CV:元類相關:__new__函式和__init__函式​zhuanlan.zhihu.com

2.1.8屬性相關

__getattr__函式、__setattr__函式、__getattribute__函式、__setattribute__函式和__dir__函式:

初識CV:屬性相關:__getattr__函式、__setattr__函式、__getattribute__函式、__setattribute__函式和__dir__函式:​zhuanlan.zhihu.com

2.1.9 屬性描述符

__get__函式、__set__函式和__delete_函式:

初識CV:屬性描述符:__get__函式、__set__函式和__delete_函式​zhuanlan.zhihu.com

2.1.10協程

__await__函式、__aiter__函式、__anext__函式、__aenter__函式和__aexit__函式

2.2數學運算

2.2.1 一元運算子

__neg__ (-)、__pos__ (+)和__abs__函式。

2.2.2二元運算子

__lt__ (<)、__le__ (<=)、__eq__ (==)、__ne__ (!=)、__gt__ (>)和__ge__ (>=)。

2.2.3算術運算子

__add__ (+)、__sub__ (-)、__mul__ (*)、__truediv__ (/)、__floordiv__ (//)、__mod__ (%)、__divmod__ 或divmod()、__pow__ 或pow() (**)和__round__ 或round()。

2.2.4反向算術運算子

__radd__、__rsub__、__rmul__、__rtruediv__、__rfloordiv__、__rmod__、__rdivmod__和__rpow__。

2.2.5增量賦值算術運算子

__iadd__、__isub__、__imul__、__ifloordiv__和__ipow__。

2.2.6位運算子

__invert__ (~)、__lshift__ (<<)、__rshift__ (>>)、__and__ (&)、__or__ (|)和__xor__ (^)。

2.2.7反向位運算子

__rlshift__、__rrshift__、__iand__、__ixor__和__ior__。

2.2.8增量賦值運算子

__ilshift__、__irshift__、__iand__、__ixor__和__ior__。

2.3 其他魔法函式

__ unicode__()函式,__ delattr__()函式, __ del__()函式, __dict__()函式,__all__()函式:

初識CV:其他魔法函式:__ unicode__(),__ delattr__(), __ del__(), __dict__(),__all__()​zhuanlan.zhihu.com

[1][2][3][4]

參考

  1. ^Python類特殊成員(屬性和方法)http://c.biancheng.net/view/2367.html
  2. ^Python中內建屬性__getattribute__的用法總結https://blog.csdn.net/yitiaodashu/article/details/78974596
  3. ^Python3基礎 __delattr__ 在一個屬性被刪除時的行為https://www.cnblogs.com/xingchuxin/p/10425683.html
  4. ^Python __exit__,__enter__函式with語句的組合應用http://blog.sina.com.cn/s/blog_13cc013b50102wvp1.html
編輯於 05-29 原文連結:https://zhuanlan.zhihu.com/p/344951719