Mocking class constructor default parameters in Python

柔情痞子 提交于 2019-12-24 01:18:09

问题


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'?


回答1:


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'



回答2:


Would a new mock class do?

class Amock(A):
  def __init__(self, details='newdefault'):
      super(Amock, self).__init__(details=details)


来源:https://stackoverflow.com/questions/36704191/mocking-class-constructor-default-parameters-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!