Erik Åsland
Erik Åsland

Reputation: 9782

Django/Python: How to call function from parent class within child class?

I currently have two classes, Main and Calculator. Main has multiple functions within it. I am trying to call the functions within main from within my calculator class. How do I do it?

Here is my current view...

class Main(object):
    template = ""
    favorite_number = None
    least_favorite_number = None

    def add (self, request, a, b):
        return a + b

    def subtract(self, request, a, b):
        return a - b

    def multiply(self, request, a, b):
        return a * b

    def divide(self, request, a, b):
        return a / b

    def get(self, request):
        return render(request, 'inherit/index.html')

class Calculator(Main, View):
    template = 'calculator/index.html'
    favorite_number = 20
    least_favorite_number = 2

print self.add(request, favorite_number, least_favorite_number)

Upvotes: 0

Views: 909

Answers (1)

Hybrid
Hybrid

Reputation: 7049

Your code seems to be fine, except for the fact that the print statement isn't indented properly, and therefore is not part of Calculator() There's also no point of adding self and request to the Main methods.

views.py

class Main(object):
    template = ""
    favorite_number = None
    least_favorite_number = None

    def add(a, b):
        return a + b

    def subtract(a, b):
        return a - b

    def multiply(a, b):
        return a * b

    def divide(a, b):
        return a / b

class Calculator(Main, View):
    template = 'calculator/index.html'
    favorite_number = 20
    least_favorite_number = 2

    def get(self, request):
        print self.add(self.favorite_number, self.least_favorite_number)
        return render(request, self.template, {})

Keep in mind that in order for you to see the print statement in your console, you have to actually be looking at the view. So wire in the Calculator view into urls.py, navigate to the page, and you should be able to see if the print statement is working in the console.

Upvotes: 1

Related Questions