Skip to content Skip to sidebar Skip to footer

Slighly Alter Method By Passing Function To Class Constructor In Python

I'm writing a class which needs to use slightly different code depending on the instance. I could achieve this through inheritance, but I wondered whether it would would be simpl

Solution 1:

Actually, I don't like the idea much.

First of all, you'll have random functions not belonging to any class in particular but that actually use self as arguments (although self is just a normal function argument, that's something in the code that doesn't smell very good).

Having functions wandering around in a module usually makes me uncomfortable, unless the module is just a helper module filled only with helper functions. But mixing classes and functions and these functions actually performing some work on classes' instances is kind of messy from my point of view.

Inheritance looks great here. Just redefine a different constructor for every class that needs it and, when other developers see the code they will have a better idea of what's going on. At the end of the day you need to code the logic for those functions, so why not just code it inside the classes their instances represent.

Also, you may want to take a look to the Factory Pattern. It is a creational pattern that might fill your needs. The idea you have makes sense, but the implementation is rather messy. By following a pattern you make sure to take the rights step to create nice code, understandable and reusable. Take also a look at several creational patterns, maybe one of them is what you're looking for.

Hope this helps!

Post a Comment for "Slighly Alter Method By Passing Function To Class Constructor In Python"