python - 每次执行方法后暂停

标签 python time

我尝试在每次执行方法后添加暂停,有办法自动执行吗? 其实我有这样的事情:

import time
def test (arg):
    print arg
    time.sleep(0.1)
class Foo (Object):
   def __init__ (self, a, b):
       self.a = a
       self.b = b
       time.sleep(0.1)
   def printer (self, arg):
       print arg
       time.sleep(0.1)

最佳答案

这与 @Fedor Gogolev 的解决方案基本相同, 不同之处在于它使用类装饰器而不是元类。

import time
import inspect
import functools

def sleep(f):
    @functools.wraps(f)    
    def wrapper(*args, **kwargs):
        result = f(*args, **kwargs)
        time.sleep(0.1)
        return result
    return wrapper

def sleeper(cls):
    for name, method in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls, name, sleep(method))
    return cls

@sleeper
class Foo(object):
   def __init__(self, a, b):
       self.a = a
       self.b = b
   def printer(self, arg):
       print arg


f = Foo(1,2)
f.printer('hi')

关于python - 每次执行方法后暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11826389/

相关文章:

php - 如何根据服务器时间设置第二天开始的cookie?

python - Linux 中的安全 Python 环境

python - 使用 Python 脚本在 Linux 中创建用户帐户时遇到问题

python - Shapefile 到 2D 网格作为稀疏矩阵

PHP time() 改变小时和秒而不是分钟?

python - 连续的同行函数调用与解包

python - 如何根据 Numpy 数组的内容替换其特定条目

python - Django 中的 override_settings 和 modify_settings 有什么区别?

c++ - 如何在 C++ 列表中保存计时时间

php - 如何检查日期是否已过