python - 使用两个不同的装饰器实现装饰所有类方法的元类

标签 python decorator metaclass class-method

我在我写的这个元类装饰器上应用装饰器的实现有问题:

def decorateAll(decorator):
    class MetaClassDecorator(type):

        def __new__(meta, classname, supers, classdict):
            for name, elem in classdict.items():
                if type(elem) is FunctionType:
                    classdict[name] = decorator(classdict[name])
            return type.__new__(meta, classname, supers, classdict)
    return MetaClassDecorator

这是我在其中使用元类的类:

class Account(object, metaclass=decorateAll(Counter)):

    def __init__(self, initial_amount):
        self.amount = initial_amount

    def withdraw(self, towithdraw):
        self.amount -= towithdraw

    def deposit(self, todeposit):
        self.amount += todeposit

    def balance(self):
        return self.amount

当我将一个像这样实现的装饰器传递给装饰器元类时,一切似乎都很好:

def Counter(fun):
    fun.count = 0
    def wrapper(*args):
        fun.count += 1
        print("{0} Executed {1} times".format(fun.__name__, fun.count))
        return fun(*args)
    return wrapper

但是当我使用以这种方式实现的装饰器时:

class Counter():

    def __init__(self, fun):
        self.fun = fun
        self.count = 0

    def __call__(self, *args, **kwargs):
        print("args:", self, *args, **kwargs)
        self.count += 1
        print("{0} Executed {1} times".format(self.fun.__name__, self.count))
        return self.fun(*args, **kwargs)

我遇到了这个错误:

line 32, in __call__
return self.fun(*args, **kwargs)
TypeError: __init__() missing 1 required positional argument: 'initial_amount'

为什么?将两个装饰器实现与其他函数一起使用不会给我带来问题。我认为问题与我试图装饰的方法是类方法这一事实有关。我错过了什么吗?

最佳答案

您需要将Counter 实现为可调用的描述符。当在描述符上执行 __get__ 时,您模拟将描述符绑定(bind)到传递给它的实例。加上在每个方法/对象的基础上存储计数。

这段代码:

import collections
import functools
import types


def decorateAll(decorator):
    class MetaClassDecorator(type):

        def __new__(meta, classname, supers, classdict):
            for name, elem in classdict.items():
                if type(elem) is types.FunctionType:
                    classdict[name] = decorator(classdict[name])
            return type.__new__(meta, classname, supers, classdict)
    return MetaClassDecorator


class Counter(object):
    def __init__(self, fun):
        self.fun = fun
        self.cache = {None: self}
        self.count = collections.defaultdict(int)

    def __get__(self, obj, cls=None):
        if obj is None:
            return self

        try:
            return self.cache[obj]
        except KeyError:
            pass

        print('Binding {} and {}'.format(self.fun, obj))
        cex = self.cache[obj] = functools.partial(self.__call__, obj)
        return cex

    def __call__(self, obj, *args, **kwargs):
        print("args:", obj, *args, **kwargs)
        self.count[obj] += 1
        print("{0} Exec {1} times".format(self.fun.__name__, self.count[obj]))
        return self.fun(obj, *args, **kwargs)


class Account(object, metaclass=decorateAll(Counter)):

    def __init__(self, initial_amount):
        self.amount = initial_amount

    def withdraw(self, towithdraw):
        self.amount -= towithdraw

    def deposit(self, todeposit):
        self.amount += todeposit

    def balance(self):
        return self.amount


a = Account(33.5)

print(a.balance())

产生以下输出:

Binding <function Account.__init__ at 0x000002250BCD8B70> and <__main__.Account object at 0x000002250BCE8BE0>
args: <__main__.Account object at 0x000002250BCE8BE0> 33.5
__init__ Exec 1 times
Binding <function Account.balance at 0x000002250BCD8D90> and <__main__.Account object at 0x000002250BCE8BE0>
args: <__main__.Account object at 0x000002250BCE8BE0>
balance Exec 1 times
33.5

它调用描述符的 __call__ 方法,通过模拟创建类型为 functools.partial 的对象的绑定(bind),将计数存储在每个方法上。

关于python - 使用两个不同的装饰器实现装饰所有类方法的元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951318/

相关文章:

php - Zend Framework 表单、装饰器和验证 : should I go back to plain HTML?

python - 如何测试 Python 函数装饰器?

meteor - Meteor 1.4 中的装饰器

python - 以反射方式在 Python 中创建嵌套类

python - 在 Python 3 中使用元类重新定义 __init__

python - 为什么我会收到错误消息:OpenCV(4.2.0)C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:376:错误:

java - Java 和 Python 之间的多字节字符 (UnicodeEncodeError)

python - 在 Python 中将可选函数(和可选参数)传递给另一个函数?

python - 什么是 firebase fcm 的设备注册 ID,我可以在哪里提取它们?

c++ - 我们需要元类来做到这一点,还是反射就足够了?