python - Passing class names to dictionary (and parsing order) -
i have code looks following:
class action(object): ... class specificaction1(action): ... class specificaction2(action): ...
they specified in same file. before specification want put dictionary looks this:
actions = { "specificaction1": specificaction1, "specificaction2": specificaction2 }
the idea can import actions dictionary other modules , have 1 dictionary 1 canonical string representation of actions (they sent on network , other places need identifier).
is possible "class pointers" in same way function pointers? , editor complains names undefined before dictionary declared before class definitions - true?
also, if above possible can instantiate class: actions['specificaction2']()
?
classes first-class citizens in python, i.e. can treat them other object. point of view construction fine, except have define actions
dictionary @ end of file (because unlike other languages order important in python: throw referenceerror otherwise).
there's more. use metaprogramming simplify this. consider (python2.x, syntax bit different in 3.x):
actions = {} class mymeta(type): def __init__(cls, name, bases, nmspc): super(mymeta, cls).__init__(name, bases, nmspc) if name != "action": # <--- skip base class actions[name] = cls class action(object): __metaclass__ = mymeta ... class specificaction1(action): ... class specificaction2(action): ...
it automatically populate actions
dictionary class inherits action
class (because action
class has mymeta
__metaclass__
). read more metaprogramming here:
https://python-3-patterns-idioms-test.readthedocs.org/en/latest/metaprogramming.html
as actions['specificaction2']()
: yes, create new instance of class, it's valid code.
Comments
Post a Comment