简体   繁体   English

每次执行方法后暂停

[英]Make a pause after each execution of a method

I try to add a pause after each execution of method, there is a way to do it automatically ? 我尝试在每次执行方法后添加一个暂停,有一种方法可以自动执行? Actually i've something like this : 其实我有这样的事情:

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)

Here is basically the same thing as @Fedor Gogolev's solution, except that this uses a class decorator instead of a metaclass. 这与@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')

Yes, your can use metaclasses to modify your class methods in creation, and decorate every function with a special decorator. 是的,您可以使用类在创建时修改类方法,并使用特殊的装饰器装饰每个函数。 In your case it could be like this: 在您的情况下,可能是这样的:

#! /usr/bin/env python
#-*- coding:utf-8 -*-

import time

from inspect import isfunction
from functools import wraps

def sleep_decorator(func):
    @wraps(func)
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        time.sleep(0.1)
        return result
    return inner

class BaseFoo(type):

    def __new__(cls, name, bases, dct):
        for name in dct:
            if isfunction(dct[name]):
                dct[name] = sleep_decorator(dct[name])
        return type.__new__(cls, name, bases, dct)


class Foo (object):
    __metaclass__ = BaseFoo

    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def printer (self, arg):
        print arg

You could look at decorators (one could use a class decorator to apply a sleep to each class method for instance), but otherwise, no - not really. 您可以查看装饰器(例如,可以使用类装饰器向每个类方法施加睡眠),但否则,不是-并非如此。 One way or another, if you want it to sleep, you should be explicit about it. 一种或另一种方式,如果您想让它入睡,则应该对此明确。 That way, there'll be less surprises if anyone should want to re-use your code or do timings etc... etc... 这样,如果有人要重用您的代码或执行计时等操作,将不会有太多惊喜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM