python按类名切换? [英] python switch by class name?

查看:36
本文介绍了python按类名切换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently doing this, to do different things based on an object's type:

    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]()

是否可以去掉 for 循环,然后做这样的事情?

Is it possible to cut out the for loop, and do something like this?

actions[something to do with obj]()

推荐答案

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()

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

Simpler. Clearer. More extensible. Less Magic. No dictionary. No loop.

这篇关于python按类名切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆