you can create a dictionary mapping case values to functions to call. For
example::
- def function_1(...):
- ...
-
functions = {'a': function_1,
'b': function_2,
- 'c': self.method_1, ...}
+ 'c': self.method_1}
func = functions[value]
func()
For calling methods on objects, you can simplify yet further by using the
:func:`getattr` built-in to retrieve methods with a particular name::
- def visit_a(self, ...):
- ...
- ...
+ class MyVisitor:
+ def visit_a(self):
+ ...
- def dispatch(self, value):
- method_name = 'visit_' + str(value)
- method = getattr(self, method_name)
- method()
+ def dispatch(self, value):
+ method_name = 'visit_' + str(value)
+ method = getattr(self, method_name)
+ method()
It's suggested that you use a prefix for the method names, such as ``visit_`` in
this example. Without such a prefix, if values are coming from an untrusted
The decorator syntax is merely syntactic sugar, the following two
function definitions are semantically equivalent::
- def f(...):
+ def f(arg):
...
f = staticmethod(f)
@staticmethod
- def f(...):
+ def f(arg):
...
The same concept exists for classes, but is less commonly used there. See
class C(ABC):
@abstractmethod
- def my_abstract_method(self, ...):
+ def my_abstract_method(self, arg1):
...
@classmethod
@abstractmethod
- def my_abstract_classmethod(cls, ...):
+ def my_abstract_classmethod(cls, arg2):
...
@staticmethod
@abstractmethod
- def my_abstract_staticmethod(...):
+ def my_abstract_staticmethod(arg3):
...
@property
class C(ABC):
@classmethod
@abstractmethod
- def my_abstract_classmethod(cls, ...):
+ def my_abstract_classmethod(cls, arg):
...
class C(ABC):
@staticmethod
@abstractmethod
- def my_abstract_staticmethod(...):
+ def my_abstract_staticmethod(arg):
...
class C:
@classmethod
- def f(cls, arg1, arg2, ...): ...
+ def f(cls, arg1, arg2): ...
The ``@classmethod`` form is a function :term:`decorator` -- see
:ref:`function` for details.