Django / Python:如何从子类中的父类调用函数?

时间:2015-12-01 23:32:04

标签: python django inheritance

我目前有两个课程,MainCalculatorMain内有多个功能。我试图在我的计算器类中调用main中的函数。我该怎么做?

这是我目前的看法......

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)

1 个答案:

答案 0 :(得分:1)

您的代码似乎没问题,但print语句没有正确缩进的事实,因此不属于Calculator()的一部分也没有任何意义。将selfrequest添加到Main方法。

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, {})

请记住,为了让您在控制台中看到print语句,您必须实际查看视图。因此,在Calculator视图中连接到urls.py,导航到该页面,您应该能够看到print语句是否在控制台中正常工作。