M. *_*ley 5 python dictionary control-flow
我有一个很长的if-elif链,像这样:
class MyClass:
def my_func(self, item, value):
if item == "this":
self.do_this(value)
elif item == "that":
self.do_that(value)
# and so on
Run Code Online (Sandbox Code Playgroud)
我发现难以阅读,所以我更喜欢使用字典:
class MyClass:
def my_func(self, item, value):
do_map = {
"this" : self.do_this,
"that" : self.do_that,
# and so on
}
if item in do_map:
do_map[item](value)
Run Code Online (Sandbox Code Playgroud)
每次调用函数时重新创建映射都很愚蠢.我怎样才能重构这个类,以便为所有实例创建一次字典?我可以以某种方式do_map变成一个类成员,但仍然映射到实例方法?
您必须在__init__方法中初始化地图:
def __init__(self):
self.do_map = dict(this=self.do_this, that=self.do_that)
Run Code Online (Sandbox Code Playgroud)
或使用string-and-getattr方法:
class Foo(object):
do_map = dict(this='do_this', that='do_that')
def my_func(self, item, value):
if item in do_map:
getattr(self, do_map[item])(value)
Run Code Online (Sandbox Code Playgroud)