首页 > 解决方案 > 实例属性如何传递给装饰器内部函数?

问题描述

我最近研究了装饰器如何在 python 中工作,并找到了一个将装饰器与嵌套函数集成的示例。代码在这里:

def integer_check(method):
    def inner(ref):
        if not isinstance(ref._val1, int) or not isinstance(ref._val2, int):
            raise TypeError('val1 and val2 must be integers')
        else:
            return method(ref)
    return inner


class NumericalOps(object):
    def __init__(self, val1, val2):
        self._val1 = val1
        self._val2 = val2

    @integer_check
    def multiply_together(self):
        return self._val1 * self._val2

    def power(self, exponent):
        return self.multiply_together() ** exponent

y = NumericalOps(1, 2)

print(y.multiply_together())
print(y.power(3))

我的问题是内部函数参数(“ref”)如何访问实例属性(ref._val1 和 ref._val2)?似乎 ref 等于实例,但我不知道它是如何发生的。

标签: pythonpython-decoratorsnested-function

解决方案


好吧,我前段时间发现的关于该self论点的一种解释是:

y.multiply_together()

大致相同

NumericalOps.multiply_together(y)

因此,现在您使用该装饰器,它返回inner需要ref参数的函数,所以我看到大致是这样发生的(在较低级别上):

NumericalOps.inner(y)

因为inner“替代”multiply_together的同时还增加了额外的功能


推荐阅读