0

web2py 示例 33我们看到:

db.purchase.insert(buyer_id=form.vars.buyer_id,  
   product_id=form.vars.product_id, 
   quantity=form.vars.quantity)

但我认为应该有一些方法可以减少重复性。也许这个?

db.purchase.insert(**dict( [k = getattr(form.vars, k) for k in "buyer_id product_id quantity".split()]))
4

3 回答 3

6

For me, DRY means 1) not repeating actual code, and 2) (and more important) not repeating information; i.e. there should be one place that each item of information exists.

In this instance, you're really just repeating a pattern, and I think that's fine. The second example is much harder to read; why complicate it just to save a few characters?

于 2012-07-23T18:26:19.623 回答
2

You could avoid repeating form.vars:

vars = form.vars
db.purchase.insert(
    buyer_id=vars.buyer_id,  
    product_id=vars.product_id, 
    quantity=vars.quantity)

There is still some repetition, but I think it's better to leave it with some repetition rather than making your code hard to read.

于 2012-07-23T18:25:48.557 回答
0

如果你能做的只有这三件事

db.purchase.insert(**form.vars)

否则我认为原始代码很枯燥

但我想你可以

to_insert = {"product_id":form.vars.product_id,"quantity":form.vars.quantity,"buyer_id":form.vars.buyer_id}
db.purchase.insert(**to_insert) 

这类似于您的第二个示例,但更具可读性和简单性(python 的一些原则)

于 2012-07-23T18:30:29.953 回答