在 Python 中模拟类构造函数的默认参数 [英] Mocking class constructor default parameters in Python

查看:34
本文介绍了在 Python 中模拟类构造函数的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法只模拟类构造函数的默认参数?例如,如果我有这个类:

 A 类(对象):def __init__(self, details='example'):self.details = 细节

有没有办法只模拟 details 参数的默认值,例如 details='test'?

解决方案

这当然是最简单的:

 类 TestA (A):def __init__(self, details='test'):super(TestA, self).__init__(details)

如果您不能在不更改其他地方的代码的情况下使用 TestA,那么您可以尝试更直接的方法:

<预><代码>>>>A().详情'例子'>>>A.__old_init = A.__init__>>>A.__init__ = lambda self, details='test': self.__old_init(details)>>>A().详情'测试'

如果你愿意走那么远,为什么不以整洁的方式做呢?

A 类(对象):_DEFAULT_DETAILS = '细节'def __init__(self, details=None):如果详细信息为无:self.details = self._DEFAULT_DETAILS别的:self.details = 细节

现在您可以覆盖默认值而无需使用任何技巧:

A._DEFAULT_DETAILS = '测试'

Is there a way to mock just the default parameters of a class constructor? For example, if I have this class:

  class A (object):
      def __init__(self, details='example'):
          self.details = details

Is there a way to a mock just the default value of the details argument, eg to details='test'?

解决方案

Surely this is simplest:

  class TestA (A):
      def __init__(self, details='test'):
          super(TestA, self).__init__(details)

If you're not able to use TestA without changing code elsewhere, then you could try something a bit more direct:

>>> A().details
'example'
>>> A.__old_init = A.__init__
>>> A.__init__ = lambda self, details='test': self.__old_init(details)
>>> A().details
'test'

If your willing to go that far, though, why not do it the tidy way?

class A (object):
    _DEFAULT_DETAILS = 'details'

    def __init__(self, details=None):
        if details is None:
            self.details = self._DEFAULT_DETAILS
        else:
            self.details = details

Now you can override the default value without resorting to any trickery:

A._DEFAULT_DETAILS = 'test'

这篇关于在 Python 中模拟类构造函数的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆