我想让这个 Destination()
函数使用多个变量,因为我不想一次又一次地编写它。我使它与两个变量相等,但它不起作用。如何解决这个问题?
def index(request):
a,b = Destination()
a.desc = 'Hello, How are you!'
a.img = '01.jpg'
b.desc = 'Hello, How are you!'
b.img = '02.jpg'
target = [a,b]
context = {
'target': target
}
return render(request, 'index.html', context)
最佳答案
如果你写 a, b = ...
你执行 iterable unpacking [PEP-3132] .由于 Destination
对象可能不可迭代,因此这行不通。
例如,您可以在此处使用列表理解生成两个 Destination
,这甚至可以跳过第二次分配 target = [a, b]
的需要:
def index(request):
<b>target</b> = a, b = <b>[</b>Destination() <b>for __ in range(2)]</b>
a.desc = 'Hello, How are you!'
a.img = '01.jpg'
b.desc = 'Hello, How are you!'
b.img = '02.jpg'
context = {
'target': target
}
return render(request, 'index.html', context)
鉴于 desc
是 Destination(..)
的构造函数的参数,您也可以省略它:
def index(request):
target = a, b = [Destination(<b>desc='Hello, How are you!'</b>) for __ in range(2)]
a.img = '01.jpg'
b.img = '02.jpg'
context = {
'target': target
}
return render(request, 'index.html', context)
严格来说,您可以制作某种生成器,例如:
def generator(f, n, *args, **kwargs):
return [f(*args, **kwargs) for __ in range(n)]
那么上面的可以替换为:
def index(request):
target = a, b = <b>generator(</b>Destination, 2, desc='Hello, How are you!'<b>)</b>
a.img = '01.jpg'
b.img = '02.jpg'
context = {
'target': target
}
return render(request, 'index.html', context)
这因此略微减少了样板代码的数量,尽管它可能会降低可读性,因为现在读者需要先检查 generator
函数。
关于python - 如何使这个功能在django 的views.py 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56984757/