0

Python の関数型とクラス型、引数と引数なしのデコレータのさまざまな化身の例は何ですか?

4

1 に答える 1

3
def decorator_noarg(f):
    def wrapper(*args, **kwargs):
        print("Inside decorator-function, WITHOUT arg.")
        return f(*args, **kwargs)
    return wrapper

def decorator_witharg(dec_arg):
    def real_decorator(f):
        def wrapper(*args, **kwargs):
            print("Inside decorator-function, WITH arg: %s" % (dec_arg))
            return f(*args, **kwargs)
        return wrapper
    return real_decorator

class decoratorclass_noarg(object):
    f = None
    def __init__(self, f):
        def host_wrapper(*arg, **kwargs):
            print("Inside decorator-class, WITHOUT arg.")

            # We lose the original instance of the object.
            return f(test_class(), *arg, **kwargs)

        self.f = host_wrapper

    def __call__(self, *args, **kargs):
        return self.f(*args, **kargs)

class decoratorclass_witharg(object):
    f = None
    def __init__(self, dec_arg):
        def decorator(host_method):
            def host_wrapper(host_obj, *arg, **kwargs):
                print("Inside decorator-class, WITH arg: %s" % (dec_arg))
                return host_method(host_obj, *arg, **kwargs)
            return host_wrapper
        self.f = decorator

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

class decorator_on_function_noarg(object):
    f = None

    def __init__(self, f):
        self.f = f
        pass

    def __call__(self):
        print("Inside decorator-on-function class, without arg.")
        return self.f()

class decorator_on_function_witharg(object):
    f = None

    def __init__(self, dec_arg):
        def decorator(host_method):
            def host_wrapper(*arg, **kwargs):
                print("Inside decorator-on-function class, with arg: %s" % (dec_arg))
                return host_method(*arg, **kwargs)
            return host_wrapper
        self.f = decorator

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

def decorator_function_on_method_noarg(f):
    print("Inside decorator-function on method, without arg.")
    return f

def decorator_function_on_method_witharg(dec_arg):
    def wrapper(f):
        print("Inside decorator-function on method, with arg: %s" % (dec_arg))
        return f

# Testing calls.

class test_class(object):
    #@decorator_witharg(44)
    #@decorator_noarg
    #@decoratorclass_witharg(1)
    #@decoratorclass_noarg
    #@decorator_function_on_method_noarg
    #@decorator_function_on_method_witharg(33)
    def test_func(self, arg1, arg2):
        print("Inside: %s, %s" % (arg1, arg2))
        return 123

#@decorator_on_function_noarg
#@decorator_on_function_witharg(22)
def test_func():
    print("Inside test_func.")

#test_class().test_func(33, 44)
#test_func()
于 2012-08-18T20:35:03.363 に答える