您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – TypeError:尝试模拟classmethod时的未绑定方法

5b51 2022/1/14 8:23:10 python 字数 1828 阅读 569 来源 www.jb51.cc/python

此脚本失败: import mock class MyClass(object): @classmethod def my_method(cls): print('my_method') def mocked_method(cls): print('I want this method to get called') with mock.patch.

概述

import mock

class MyClass(object):

    @classmethod
    def my_method(cls):
        print('my_method')

def mocked_method(cls):
    print('I want this method to get called')

with mock.patch.object(MyClass,'my_method',mocked_method):
    MyClass.my_method()

例外:

Traceback (most recent call last):
  File "/home/foo/tmp/test_mocking_classmethod.py",line 14,in <module>
    MyClass.my_method()
TypeError: unbound method mocked_method() must be called with MyClass instance as first argument (got nothing instead)

只需手动将目标包装在classmethod装饰器中:

with mock.patch.object(MyClass,classmethod(mocked_method)):
    MyClass.my_method()

这里我手动应用了@classmethod装饰器,但您也可以直接在目标函数上使用它作为装饰器:

@classmethod
def mocked_method(cls):
    print('I want this method to get called')

with mock.patch.object(MyClass,mocked_method):
    MyClass.my_method()

演示:

>>> import mock
>>> class MyClass(object):
...     @classmethod
...     def my_method(cls):
...         print('my_method')
... 
>>> def mocked_method(cls):
...     print('I want this method to get called')
... 
>>> with mock.patch.object(MyClass,classmethod(mocked_method)):
...     MyClass.my_method()
... 
I want this method to get called

总结

以上是编程之家为你收集整理的python – TypeError:尝试模拟classmethod时的未绑定方法全部内容,希望文章能够帮你解决python – TypeError:尝试模拟classmethod时的未绑定方法所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶