python - 实例属性如何传递给装饰器内部函数?
问题描述
我最近研究了装饰器如何在 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 等于实例,但我不知道它是如何发生的。
解决方案
好吧,我前段时间发现的关于该self
论点的一种解释是:
y.multiply_together()
大致相同
NumericalOps.multiply_together(y)
因此,现在您使用该装饰器,它返回inner
需要ref
参数的函数,所以我看到大致是这样发生的(在较低级别上):
NumericalOps.inner(y)
因为inner
“替代”multiply_together
的同时还增加了额外的功能
推荐阅读
- python - 为什么对内存操作使用同步编程更好?
- python - 如何在 Python 中使用 re() 并在“If”语句中返回捕获组?
- java - 如何存储值以创建同一类的多字段对象
- google-bigquery - BigQuery:选择具有 ARRAY 类型字段的最近的一组行
- excel - 如何根据excel VBA中的选择添加可选复选框
- javascript - 如何在特定时间继续单个 Redux Actions
- css - 如何在 Angular 中的 Mat 选择中测试 Input 和 mat 选项
- c# - 显示属性名称给出资源找不到错误
- javascript - js中改变字体大小的函数。如何添加缩放限制?
- php - PHP 7 的路径 - 使用“|” 特点