Python:如何调用来自数组的方法?

标签 python methods switch-statement

这是我的类,它有常量:

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/

相关文章:

Java:方法的继承

Java - Switch 语句和大括号

javascript - 如何让输入字母时出现图像?

python - 动态地将值传递给声明对象/变量

python - PyCharm 类型提示 : return type not detected

python - 如何检查 python 类是否具有特定方法?

javascript - 重构异步 CoffeeScript 执行 AJAX

java - Switch 语句而不是 if 语句

Python:对本地服务器的请求不起作用

python - 使用辅助 y 轴时如何标记 y 轴?