对于自定义的类,如果你希望其实例表现得像一个函数,可以通过定义__call__方法来实现,当实例被当作函数调用时(即在实例后面加上圆括号),Python会自动执行这个__call__方法。 class Greeter: def __init__(self, greeting): self.greeting = greeting def __call__(self, name):
class Counter: def __init__(self): self.count = 0 def __call__(self): ...
可以利用__call__来记录或改变对象的状态。 假设我们需要监控一个应用程序中各个函数的运行时间,可以利用__call__方法来实现这样的功能。 示例代码: import time class PerformanceMonitor: def __init__(self, func): self.func = func self.call_count = 0 # 添加计数器 def __call__(self, *args, *...
def __call__(self, *args, **kwargs): start_time = time.time() result = self.func(*args, **kwargs) end_time = time.time() print(f"{self.func.__name__} executed in {end_time - start_time:.4f}s") return result @TimerDecorator def example_function(): time.sleep(1) print(...
def __init__(self,fun): #初始化函数里调入外部fun函数 self._fun=fun print(fun.__name__+" is running!") def __call__(self,*args): #__call__函数在类为装饰器时自动调用 return self._fun(*args) @logit #使用logit类装饰器,自动调用__call__函数 ...
time() print(f"Function {self.func.__name__} took {end_time - start_time} seconds to run.") return result Python Copy在这个示例中,我们定义了一个名为Timer的类,它接受一个函数作为参数。在__call__()方法中,我们记录了函数执行前后的时间,并打印出执行的耗时。
Python的self参数有时真让人抓狂,比如,你必须在每一个类的方法里显示定义self,然后,它会霸占不需要它们的地方。 [python]view plaincopy 1. class Foo(object): 2. 9 3. def __init__(self,x): 4. self.x = x 5. 6. def bar(self,y): ...
如果给定类的实例是可调用的,那么需要在底层类中实现.__call__()特殊方法。这个方法能够像调用普通 Python 函数那样调用类的实例。 与其它特殊方法不同,.__call__()对它必须接受的参数没有特殊要求。它和其它实例方法一样,以self作为第一个参数,并且可以根据需要接受任意多的额外参数。
obj.active_call_function() 二、通过getattr实现 1 通过函数名调用同一个类内的函数 classTestA:def__init__(self): self.config_dict = {"be_called_function_name":"be_called_function", }passdefactive_call_function(self):print("here is active_call_function.")# getaattr(module_name, function...
This all means that you don’t pass the reference to self in this case because self is the parameter name for an implicitly passed argument that refers to the instance through which a method is being invoked. It gets inserted implicitly into the argument list. How to Define a Function: Use...