【发布时间】:2019-11-18 03:39:57
【问题描述】:
我正在尝试使用 Python 中的装饰器,并尝试从 botocore 库中实现 CachedProperty 装饰器的一个版本,但一直遇到错误:
TypeError: 'CachedProperty' 对象不可调用。
我今天已经在谷歌上搜索了一段时间,但我发现的示例似乎与我的问题并不直接对应。它们主要与人们试图调用 int 和失败之类的对象有关。
当我单步执行代码时,装饰器在 CachedProperty 中调用 __init__ 时,当我导入 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
我从 botocore 中提取的 CachedProperty 类:
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
【问题讨论】:
标签: python python-3.x python-decorators callable-object