在Raymond Hettinger 在PyCon 2015上的演讲" 超级考虑超级发言 "中,他解释了super在多重继承环境中使用Python 的优势.这是雷蒙德在演讲中使用的一个例子:
class DoughFactory(object):
def get_dough(self):
return 'insecticide treated wheat dough'
class Pizza(DoughFactory):
def order_pizza(self, *toppings):
print('Getting dough')
dough = super().get_dough()
print('Making pie with %s' % dough)
for topping in toppings:
print('Adding: %s' % topping)
class OrganicDoughFactory(DoughFactory):
def get_dough(self):
return 'pure untreated wheat dough'
class OrganicPizza(Pizza, OrganicDoughFactory):
pass
if __name__ == '__main__':
OrganicPizza().order_pizza('Sausage', 'Mushroom')
Run Code Online (Sandbox Code Playgroud)
有人在台下问雷蒙德有关使用的差异self.get_dough(),而不是super().get_dough().我对Raymond的简要回答并不是很了解,但我编写了这个例子的两个实现来看看差异.两种情况的输出相同:
Getting dough
Making pie with pure untreated wheat dough
Adding: Sausage
Adding: …Run Code Online (Sandbox Code Playgroud) 在pytest文档中,它说您可以自定义assert失败时的输出消息。我想assert在测试返回错误状态代码的REST API方法时自定义消息:
def test_api_call(self, client):
response = client.get(reverse('api:my_api_call'))
assert response.status_code == 200
Run Code Online (Sandbox Code Playgroud)
所以我试图在其中放入一段代码 conftest.py
def pytest_assertrepr_compare(op, left, right):
if isinstance(left, rest_framework.response.Response):
return left.json()
Run Code Online (Sandbox Code Playgroud)
但是问题是left的实际值,response.status_code因此它是int而不是Response。但是,默认的输出消息抛出类似以下内容的消息:
E断言400 == 201 E +其中400 = .status_code
说错误400来自status_code对象的属性Response。
我的观点是,对要评估的变量有一种自省。因此,如何以一种舒适的方式自定义断言错误消息,以获得与上述示例类似的输出?