python按类名切换?

Luc*_*ucy 2 python syntax switch-statement

我目前正在这样做,根据对象的类型做不同的事情:

    actions = {
        SomeClass: lambda: obj.name
        AnotherClass: lambda: self.normalize(obj.identifier)
        ...[5 more of these]...
    }

    for a in actions.keys():
        if isinstance(obj, a):
            return actions[a]()
Run Code Online (Sandbox Code Playgroud)

是否可以删除for循环,并执行类似的操作?

actions[something to do with obj]()
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 6

class SomeClass( object ):
....
    def action( self ):
        return self.name

class AnotherClass( object ):
....
    def action( self ):
        return self.normalize( self.identifier )

[5 more classes like the above two]

a.action()
Run Code Online (Sandbox Code Playgroud)

简单.清晰.更具扩展性.减少魔法.没有字典.没有循环.