len是python的内置函数吗_Python3.6中是否可以模仿内置len()函数?

在Python3.6中,可以模拟内置的len()函数吗?在

我有一个类,它定义了一个依赖于len()函数的简单方法,如下所示:class MyLenFunc(object):

def is_longer_than_three_characters(self, some_string):

return len(some_string) > 3

我试图为这个方法编写一个单元测试,但是我无法模拟出len()函数而不产生错误。

以下是我目前所掌握的情况:

^{pr2}$

我发现了另一个SO-question/answerhere,这表明不可能模仿内置函数,因为它们是不可变的。然而,我发现了另外两个网站here和{a3},它们提出了不同的建议。我在上面的单元测试类中的尝试是直接从这些网站中的后者获得的(是的,我已经尝试了其中提到的其他技术)。所有这些都以相同的错误结束)。在

我得到的错误对于发布完整的内容来说是相当长的,所以我将剪去它的重复部分(您将看到它是从错误消息的最后部分递归而来的)。错误文本如下:ERROR: test_len_function_is_called (__main__.TestMyLenFunc)

----------------------------------------------------------------------

Traceback (most recent call last):

File "C:\Python36\Lib\unittest\mock.py", line 1179, in patched

return func(*args, **keywargs)

File "C:/Python/scratchpad/my_len_func_tests.py", line 16, in test_len_function_is_called

test_object.is_longer_than_three_characters(test_string)

File "C:\Python\scratchpad\my_len_func.py", line 3, in is_longer_than_three_characters

return len(some_string) > 3

File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__

return _mock_self._mock_call(*args, **kwargs)

File "C:\Python36\Lib\unittest\mock.py", line 949, in _mock_call

_call = _Call((args, kwargs), two=True)

File "C:\Python36\Lib\unittest\mock.py", line 1972, in __new__

_len = len(value)

...

(Repeat errors from lines 939, 949, and 1972 another 95 times!)

...

File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__

return _mock_self._mock_call(*args, **kwargs)

File "C:\Python36\Lib\unittest\mock.py", line 944, in _mock_call

self.called = True RecursionError: maximum recursion depth exceeded while calling a Python object

----------------------------------------------------------------------

Ran 1 test in 0.004s

FAILED (errors=1)

提前致谢。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值