程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python magic method (4):__ call __ (self, *args, **kwargs) method

編輯:Python

Python There are some magical ways to do it , They are always surrounded by double underscores , They are object-oriented Of Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .

function

Allow and define the behavior of an object when it is called like a function .

Parameters

self Represents the object itself ,args and kwargs Represents two indefinite length parameters .


Return value

Any number and type of objects .

Example

class MyText(object):
def __call__(self, *args, **kwargs):
my_sum = 0
for item in args:
my_sum += item
return my_sum
sample = MyText()
print(sample(1, 2, 3, 4, 5))

__call__() It's a kind of magic method, Implementing this method in a class can make instances of that class ( object ) Called like a function . By default, this method is not implemented in the class . Use callable() Method can determine whether an object can be called .

__call__() Method is actually used to turn an instantiated object of a class into a callable object , That is to say, an instantiated object of a class becomes a callable object , As long as the class implements __call__() The method will do .

class People(object):
def __init__(self, name):
self.name = name
def __call__(self):
print("hello " + self.name)
a = People(' No taboo !')
a.__call__() # Call method 1
a() # Call method 2

When writing a class , If it's written __call__() Method , When the instantiated object is called, there will be Instance object point __call__() and object() These two ways of use have the same effect , That is, calling method 1 has the same effect as calling method 2 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved