魔術方法介紹
以雙下劃線作為前綴和後綴的方法名是 Python 中特定使用的保留方法。例如, init 方法用於對象構造器,或者 call 方法用於使對象可調用。我們稱這些方法為鄧德方法,其中鄧德指的是雙 under(下劃線)。這些鄧德法又被稱為魔法 -然而,並沒有什麼神奇的與之相關。Python 社區中有許多開發人員不太喜歡「魔法」這個詞,因為它給人一種不鼓勵使用這種方法的感覺,但矛盾是事實。
理解可調用函數
當對象在 call() 函數中定義時, Python 中的對象被稱為可調用的。相同的功能可以定義為 x(arg 1,arg2,…) ,這是 x.call(arg1,arg 2,…) 的縮寫。
注意:callable()方法返回一個布爾值,該值表示對象是否看起來是可調用的。如果對象是可調用的,此函數返回真;否則,它返回 False。此外,即使對象不可調用,該函數也可能返回 True。然而,如果這個方法返回 False,那麼這個對象是不可調用的。
此外,Python 類總是可調用的。因此,我們總是可以將 callable() 函數用於類的對象,而不是類本身。
為了理解 Python callable() 函數的行為,讓我們考慮以下示例。
示例:
# creating a class
class Employee:
n = 0
# defining a function
def __init__(self, emp_id):
self.i = emp_id
# instantiating the class
x = Employee(15)
# checking if the class and object are callable or not
print('Employee Class is callable = ', callable(Employee))
print('Employee object is callable = ',
輸出:
Employee Class is callable = True
Employee object is callable = False
說明:
在上面的例子中,我們定義了一個類 Employee ,它接受一個變數 n = 0 。然後我們定義了一個函數並實例化了這個類。最後,我們使用 callable() 函數檢查了類及其對象是否可調用。
讓我們考慮一個 調用 __() 函數的例子。
示例:
# creating Person Class
class Person:
person_id = 0
person_name = ""
# defining an initializing function
def __init__(self, personid, personname):
self.person_id = personid
self.person_name = personname
# defining a callable function
def __call__(self, *args, **kwargs):
print('Printing Arguments')
print(*args)
print('Printing Keyword Arguments')
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# instantiating the class
m = Person(15, 'George')
# printing the object
print(m)
# checking if the object is callable or not
print("The Person object is callable: ", callable
輸出:
<__main__.person object="" at="">
The Person object is callable: True
說明:
在上例中,我們定義了 Person 類和變數 person_id = 0 和Person _ name =「」。然後我們定義了初始化函數和可調用函數。最後,我們已經實例化了類,列印了對象,並檢查了對象是否可調用。因此,person 對象看起來是可調用的。
此外,我們可以觀察到,我們使用了 *args 來允許傳遞變數參數, **kwargs 來允許將命名參數傳遞給 call() 方法。
現在,讓我們考慮另一個例子,我們將使用可調用()函數來檢查對象是否可調用,然後將對象作為函數調用。
示例:
if callable(m):
m()
m(15, 30)
m.__call__(15, 30)
m(15, 30, {'a': 4, 'b': 8})
m(15, 'B', personname = 'George', personid = 50)
輸出:
Printing Arguments
Printing Keyword Arguments
Printing Arguments
15 30
Printing Keyword Arguments
Printing Arguments
15 30
Printing Keyword Arguments
Printing Arguments
15 30 {'a': 4, 'b': 8}
Printing Keyword Arguments
Printing Arguments
15 B
Printing Keyword Arguments
personname == George
personid == 50
說明:
在上面的例子中,我們定義了一個if-語句,其中如果對象 m 是可調用的,那麼該對象作為一個沒有參數的函數被調用,只有參數,有 call() 函數,有不同類型的參數,有參數和關鍵字參數。因此,已成功調用了所需的對象。
原創文章,作者:XTVIS,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129807.html
微信掃一掃
支付寶掃一掃