I have worked in low level C programming for years and I don't have enough exposure to Object oriented approaches. In C if I was developing some layered architecture then each layer has interfaces defined by function pointers. The advantage of that the whole layer can be replaced by just setting those function pointers at initialization to another layer.
I want the same thing but this time in Python. What is the coolest way to achieve that. To give a little background to my problem, I have a data generator which can output records to different mediums. The medium is specified at the configuration time. I don't want to use if or switch statements here. The best way was to use function pointers in C but what are the options available here in Python. Any Object oriented approaches are also appreciated.
Thanks
in python functions are first-class data types.
def z(a):
print(a)
def x(a):
print "hi"
functions = [z,x]
y = functions[0]
y("ok") # prints "ok"
y = functions[1]
y("ok") # prints "hi"
You can simply put the functions in a dict
{"type1": function1,
"type2": function2,
"type3": function3,
}.get(config_option, defaultfunction)(parameters, go, here)
default_function
is called if none of the keys match
If you wish you can separate out the selection an the calling
selected_function = {"type1": function1,
"type2": function2,
"type3": function3,
}.get(config_option, defaultfunction)
some_instance = SomeClass(selected_function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With