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

Special method __call__ in Python

編輯:Python

__call__ is a very special instance method in Python classes, which enables class instance objects to be used in the form of "object name()" just like calling ordinary functions.Objects in Python that can be followed by () to call execution are called callable objects.If the __call__() method is defined in the class, then the instance object of the class will also become a callable object.When the object is called, the code in the __call__() method will be executed.

class Entity:def __init__(self, x, y):self.x = xself.y = yprint("Initialize x:{0},y:{1}".format(x, y))def __call__(self, x, y):self.x, self.y = x, yprint("modified x:{0},y:{1}".format(x, y))e = Entity(1, 2) # create instancee(4, 5) # The instance can be executed like a function, passing in the x y value, modifying the x y of the object

Execute the above code, the output result is:

Initialize x:1,y:2Modified x:4,y:5

Instance objects can also be used as callable objects like functions. So, in what scenarios is this feature useful?

This needs to be combined with the characteristics of the class. The class can record data (attributes). Using this feature, you can implement class-based decorators and record the status in the class. For example, in the following example, the function is called.Times:


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