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

Python: how to call a method coming from an array?

这是我的 class,它有常量:

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对象,所以它可以访问所有“drawing”函数。我想避免大 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

first class

所以:

my_functions = {"function 1": print}

my_functions["function 1"]("Hello, world")

工作正常。

我怀疑如果您遇到问题,可能是因为您使用的密钥不可哈希...或者您只是没有使用正确的密钥?..

编辑:关于你的 edit/comment 基于 p 是 Canvas 的实例这一事实,你应该能够做到:

drawCustom[bubble](p, 100, 100, "Hello world.")

基本上将 "p" 作为 self 参数传递(因为字典中的方法未绑定到实例)。