user35915
user35915

Reputation: 1310

What is a good way to implement several very similar functions?

I need several very similar plotting functions in python that share many arguments, but differ in some and of course also differ slightly in what they do. This is what I came up with so far:

I can rule out the first option, but I'm hard pressed to decide between the second and third. So I started wondering: is there another, maybe object-oriented, way? And if not, how does one decide between option two and three?

I hope this question is not too general and I guess it is not really python-specific, but since I am rather new to programming (I've never done OOP) and first thought about this now, I guess I will add the python tag.

EDIT:

As pointed out by many, this question is quite general and it was intended to be so, but I understand that this makes answering it rather difficult. So here's some info on the problem that caused me to ask:

I need to plot simulation data, so all the plotting problems have simulation parameters in common (location of files, physical parameters,...). I also want the figure design to be the same. But depending on the quantity, some plots will be 1D, some 2D, some should contain more than one figure, sometimes I need to normalize the data or take a logarithm before plotting it. The output format might also vary.

I hope this helps a bit.

Upvotes: 1

Views: 1507

Answers (2)

idjaw
idjaw

Reputation: 26578

How about something like this. You can create a Base class that will have a method foo that is your base shared method that performs all the similar code. Then for your different classes you can inherit from Base and super the method of interest and extend the implementation to whatever extra functionality you need.

Here is an example of how it works. Note the different example I provided between how to use super in Python 2 and Python 3.

class Base:            
    def foo(self, *args, **kwargs):
        print("foo stuff from Base")
        return "return something here"


class SomeClass(Base):
    def foo(self, *args, **kwargs):
        # python 2
        #x = super(SomeClass, self).foo(*args, **kwargs)
        # python 3
        x = super().foo(*args, **kwargs)
        print(x)
        print("SomeClass extension of foo")

s = SomeClass()
s.foo()

Output:

foo stuff from Base
return something here
SomeClass extension of foo from Base

Upvotes: 1

Andrew Marderstein
Andrew Marderstein

Reputation: 237

More information needs to be given to fully understand the context. But, in a general sense, I'd do a mix of all of them. Use helper functions for "shared" parts, and use conditional statements too. Honestly, a lot of it comes down to just what is easier for you to do?

Upvotes: 0

Related Questions