Search code examples
pythoninheritanceparameter-passingsuperclass

Calculating a class parameter using a super method


I am new to Python and trying to understand what is the most correct way to do the following:

I have a base class called "Sample". It has some properties such as dp, tp, etc.

I also have several subclasses derived from this base as SampleA, SampleB, etc. They have several properties which distinct one from another. One of the properties is computed using these distinctive properties. And this calculation is quite repetitive, therefore I want to write one method and call it in every class to compute the value of the parameter.

class Sample(object):
    tp = 4
    dp = 4.2
    por = 0.007

    def common_method(self, arg1, arg2)
        return self.tp - arg1 * arg2

class SampleA(Sample)
    arg1 = 0.1
    arg2 = 2
    # I want to calculate arg3, but I don't know how to call the         
    # common_method here.

class SampleB(Sample)

.
.
.

I looked it up before asking the question but I did not see a similar question.

Thank you vert much in advance.


Solution

  • The solution is suggested by dhke in the comments of the original question:

    common_method() needs an object, but you are still in the class declaration. Has common_method() any other use? Because then you could just make it a class method and refer to it by Sample.common_method()

    Applying it into the code would be better, I think:

    class Sample(object):
        tp = 4
        dp = 4.2
        por = 0.007
    
    @classmethod
    def common_method(self, arg1, arg2)
        return self.tp - arg1 * arg2
    
    class SampleA(Sample)
        arg1 = 0.1
        arg2 = 2
        arg3 = Sample.common_method(arg1, arg2)  # 3.8
    
    class SampleB(Sample):
    
    .
    .
    .
    

    Thank you very much for helping me with this!