我在测试中从函数中引发异常时遇到问题:
### Implemetation
def MethodToTest():
myVar = StdObject()
try:
myVar.raiseError() # <--- here
return True
except Exception as e:
# ... code to test
return False
### Test file
@patch('stdLib.StdObject', autospec=True)
def test_MethodeToTest(self, mockedObjectConstructor):
mockedObj = mockedObjectConstructor.return_value
mockedObj.raiseError.side_effect = Exception('Test') # <--- do not work
ret = MethodToTest()
assert ret is False
Run Code Online (Sandbox Code Playgroud)
我想raiseError()发挥作用以引发错误.
我在SO上找到了几个例子,但没有一个符合我的需要.
如何解决E0203(access-member-before-definition)继承成员的误报错误?
例如在:
class A():
def __init__(self, param):
self._attr = param
class B(A):
def __init__(self, param):
A.__init__(self, param)
if <...> == self._attr: # <-- E0203
# ...
Run Code Online (Sandbox Code Playgroud) 我有以下架构:
\n\n +-----------------+\n | Collection |\n | |\n | |\n | |\n | |\n +-----------------+\n | ^\n | |\n Create() | |\n | |\n v | GetItem(B)\n+------------+ |\n| Item A | |\n| | |\n| +------+\n| |\n+------------+\nRun Code Online (Sandbox Code Playgroud)\n\n管理项目集合的类创建项目。这些物品可能需要收藏中的其他物品。
\n\n实际代码位于 python 中,目前将Collection其自身作为参数传递给创建的Item. 在我看来,这是一种不好的做法。Collection我可以看到的唯一改进是传递所需的几个函数Item,而不是整个实例。
例如:
\n\nclass Collection:\n GetItem(self, id):\n ...\n CreateItem(self, id):\n item = Item(id, self) # <-- pass self\n ...\n\nclass Item:\n __init__(self, id, col):\n ...\n col.GetItem(...)\nRun Code Online (Sandbox Code Playgroud)\n\n如何避免将 self 作为参数传递?或者说这是Python中的常见用法? …