我正在尝试使用 Python 中的装饰器并尝试CachedProperty
从 botocore 库中实现装饰器的一个版本,但一直遇到错误:
TypeError:“CachedProperty”对象不可调用。
我今天已经在谷歌上搜索了一段时间,但我发现的例子似乎并不直接等同于我的问题。它们主要与试图调用 int 和失败之类的对象的人有关。
当我单步执行代码时,装饰器__init__
在CachedProperty
导入时调用 ok sum_args()
,但是当我从单元测试中调用函数本身时会引发错误。
我的单元测试:
import unittest
from decorators.caching_example import sum_args
class TestCachedProperty(unittest.TestCase):
def test_sum_integers(self):
data = [1, 2, 3]
result = sum_args(data)
self.assertEqual(result, 6)
我要装饰的功能:
from decorators.caching_property import CachedProperty
@CachedProperty
def sum_args(arg):
total = 0
for val in arg:
total += val
return total
CachedProperty
我从 botocore 学到的课程:
class CachedProperty(object):
"""A read only property that caches the initially computed value.
This descriptor will only call the provided ``fget`` function once.
Subsequent access to this property will return the cached value.
"""
def __init__(self, fget):
self._fget = fget
def __get__(self, obj, cls):
if obj is None:
return self
else:
computed_value = self._fget(obj)
obj.__dict__[self._fget.__name__] = computed_value
return computed_value
查看我最初从中刷出的程序,我希望它能够将 sum 函数传递给CachedProperty
类——在运行时创建它的实例——并将结果存储在其内部实例变量中的实例self._fget
。
我实际上得到的是:
Error
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 615, in run
testMethod()
File "/Users/bradley.atkins/PycharmProjects/brad/examples/tests/decorators/test_property_cache.py", line 11, in test_sum_integers
result = sum_args(data)
TypeError: 'CachedProperty' object is not callable