python3 特殊函式 call

2021-08-29 18:49:35 字數 1207 閱讀 7909

__call__()的本質是將乙個類變成乙個函式(使這個類的例項可以像函式一樣呼叫)。

【例1】

class person(object):

def __init__(self, name, gender):

self.name = name

self.gender = gender

def __call__(self, friend):

print('my name is %s...' % self.name)

print('my friend is %s...' % friend)

p = person("mc", "male")

p("tim")

my name is mc...

my friend is tim...

【例2】

class classa(object):

def __new__(cls, *args, **kwargs):

object = super(classa, cls).__new__(cls)

print("hhha:0===>")

return object

def __init__(self, *args, **kwargs):

print("hhhb:0===>")

def __call__(self, func):

print("hhhc:0===>")

return func

a = classa()

print("hhhh:0====>")

@classa()

def hello():

print("hhhc:0===>hello")

print("hhhh:1====>")

hello()

輸出:

hhha:0===>

hhhb:0===>

hhhh:0====> //__call__()未呼叫

hhha:0===>

hhhb:0===>

hhhc:0===> //__call__()被呼叫

hhhh:1====>

hhhc:0===>hello

類生成例項時不會呼叫__call__(),但在作為裝飾器時__call__()被呼叫。

python3中的call函式

call 的本質是將乙個類變成乙個函式 使這個類的例項可以像函式一樣呼叫 class a object def init self,name,age self.name name self.age age def call self print my name is s self.name prin...

python 特殊方法之 call

call 在python中,函式其實是乙個物件 f abs f.name abs f 123 123由於 f 可以被呼叫,所以,f 被稱為可呼叫物件。所有的函式都是可呼叫物件。乙個類例項也可以變成乙個可呼叫物件,只需要實現乙個特殊方法 call 我們把 person 類變成乙個可呼叫物件 class...

python3函式語法 Python3

python3 degrees 函式 描述degrees 將弧度轉換為角度。語法以下是 degrees 方法的語法 import math math.degrees x 注意 degrees 是不能直接訪問的,需要匯入 math 模組,然後通過 math 靜態物件呼叫該方法。引數x 乙個數值。返回值...