这是我的类,它有常量:
class Bubble(models.Model):
GAUCHE = u'0'
CENTRE = u'1'
JUSTIFIE = u'2'
DROITE = u'3'
然后在另一个文件中,我像这样使用 Bulle
:
drawCustom = {
Bubble.GAUCHE: canvas.Canvas.drawString,
Bubble.CENTRE: canvas.Canvas.drawCentredString,
Bubble.JUSTIFIE: canvas.Canvas.drawAlignedString,
Bubble.DROITE: canvas.Canvas.drawRightString,
}
稍后,在这个文件中,我有
for bubble in mymodel.bubbles.all():
# bubble is an instance of the class Bubble
p = canvas.Canvas(response)
p.drawString(100, 100, "Hello world.")
# I want to avoid `drawString` and use my array `drawCustom`
# to make something like:
# p.call(drawCustom[bubble](100, 100, "Hello world."))
换句话说:p
是一个canvas.Canvas
对象,所以它可以访问所有“绘图
”功能。我想避免使用大的 if () elif ()
并制作如下内容:p.call(drawCustom[bubble](100, 100, "Hello world."))
这是我的代码,但我觉得它很丑:
for b in mymodel.bubbles.all():
# b is an instance of the class Bubble
p = canvas.Canvas(response)
if b.texte_alignement == Bulle.GAUCHE:
p.drawString(100, 100, "Hello world.")
elif b.texte_alignement == Bulle.CENTRE:
p.drawCentredString(100, 100, "Hello world.")
elif b.texte_alignement == Bulle.JUSTIFIE:
p.drawAlignedString(100, 100, "Hello world.")
elif b.texte_alignement == Bulle.DROITE:
p.drawRightString(100, 100, "Hello world.")
是否可能,如果不可能,在 Python 中的方法是什么?
最佳答案
这应该有效:
drawCustom[bubble](p, 100, 100, "Hello world.")
或者,如果您在 drawCustom
中存储方法名称而不是方法对象,您还可以:
drawCustom = {
Bubble.GAUCHE: 'drawString',
Bubble.CENTRE: 'drawCentredString',
Bubble.JUSTIFIE: 'drawAlignedString',
Bubble.DROITE: 'drawRightString',
}
func = getattr(p, drawCustom[bubble])
func(100, 100, "Hello world.")
关于Python:如何调用来自数组的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954515/