Ruby可以向Number类和其他核心类型添加方法以获得如下效果:
1.should_equal(1)
Run Code Online (Sandbox Code Playgroud)
但似乎Python无法做到这一点.这是真的?如果是这样,为什么?是否与类型无法修改的事实有关?
更新:我不想谈论猴子修补的不同定义,而是只关注上面的例子.我已经得出结论,由于你们中的一些人已经回答,所以无法做到.但我想更详细地解释为什么不能这样做,也许如果Python中有什么功能可以允许这样做.
回答你们中的一些人:我可能想要这样做的原因只是美学/可读性.
item.price.should_equal(19.99)
Run Code Online (Sandbox Code Playgroud)
这更像是英语,并清楚地表明哪个是测试值,哪个是预期值,如下所示:
should_equal(item.price, 19.99)
Run Code Online (Sandbox Code Playgroud)
这个概念就是Rspec和其他一些Ruby框架所基于的.
ruby python programming-languages fluent-interface monkeypatching
class HelloWorld(object):
def say_it(self):
return 'Hello I am Hello World'
def i_call_hello_world(hw_obj):
print 'here... check type: %s' %type(HelloWorld)
if isinstance(hw_obj, HelloWorld):
print hw_obj.say_it()
from mock import patch, MagicMock
import unittest
class TestInstance(unittest.TestCase):
@patch('__main__.HelloWorld', spec=HelloWorld)
def test_mock(self,MK):
print type(MK)
MK.say_it.return_value = 'I am fake'
v = i_call_hello_world(MK)
print v
if __name__ == '__main__':
c = HelloWorld()
i_call_hello_world(c)
print isinstance(c, HelloWorld)
unittest.main()
Run Code Online (Sandbox Code Playgroud)
这是追溯
here... check type: <type 'type'>
Hello I am Hello World
True
<class 'mock.MagicMock'>
here... check type: <class 'mock.MagicMock'>
E …Run Code Online (Sandbox Code Playgroud)