什麼是魔術方法以及常用的魔術方法

What is magic method in python ?

by yenchialu

魔術方法的樣子,兩個底下線+方法名稱+兩底下線

__魔術方法 __

為何需要魔術方法 ?

從應用上來看會發現,魔術方法與其他一般自定義方法的成效幾乎一樣,那為何還需要用這麼麻煩的方式命名?

此段說明參照

They’re mostly used for code that gets called implicitly when special syntax is used.

主要用於特殊語法時隱性調用的代碼

常用於以下場景

  • overloaded operators
    (exist in C++ and others) 重載運算符(存在於 C++ 和其他中)
  • constructor/destructor
    構造函數/析構函數
  • hooks for accessing attributes
    用於訪問屬性
  • tools for metaprogramming
    元程式等級操作

以及其他很多地方。

魔術函式別於一般自訂函數主要原因仍在於需要建立最初始的python必須做出最基礎的函式。

這些函式要能與上層C語言互動或者其他程式語言參照,同時也能與一般自定義函數做出最根本的區別。

所以絕大部分的魔術方法幾乎都是內建,除非程式需要動到整個python框架等級的操作,否則我們使用的魔術方法幾乎都是內置的,我們自定義的方法也不須參照魔術方法格式寫。

常用的魔術方法

__dict__

回傳物件的屬性名稱與值

#範例 1
#一個簡單的模組 Smartphone
#三個屬性 name,brand,price
#一個方法 on_sale
class Smartphone :
    def __init__(self,name,brand,price) :
        self.name = name
        self.brand = brand
        self.price = price
    def on_sale(self,discount) :
        self.price = self.price*(100-discount)/100
    
iphone_11 = Smartphone("iphone 11","Apple",1000)
iphone_11.on_sale(20)

print (Smartphone.__dict__) #返回所有可用的屬性(含內建與自定義屬性)
print (iphone_11.__dict__) #返回物件的自定義屬性

#執行結果
# >>> {‘__module__’: ‘__main__’,
‘__init__’: ,
‘on_sale’: ,
‘__dict__’: ,
‘__weakref__’: ,
‘__doc__’: None}

# >>> {‘name’: ‘iphone 11’, ‘brand’: ‘Apple’, ‘price’: 800.0}

__file__

回傳模組的路徑位置

#範例 2
import numpy as np
print(np.__file__)
print(np.ndarray.__file__)
#執行結果
 >>> 'C:\\Users\\Jia\\Anaconda3\\envs\\AI_L\\lib\\site-packages\\numpy\\__init__.py'
 >>>  AttributeError: type object 'numpy.ndarray' has no attribute '__file__'

__name__

直接使用時,回傳主程式(當前程式)py檔名稱

當作屬性使用時,使用模組的py檔名稱

#範例 3
print(__name__)
print(np.__name__)
print(np.ndarray.__name__)

#執行結果
>>> __main__
>>> numpy
>>> ndarray

問題回顧

  • 為何需要魔術方法?

You may also like

Leave a Comment