Python - 我试图随机调用一个函数,但不断收到错误

时间:2013-06-08 18:26:03

标签: python

我试图从mathsum方法调用 init 方法中列出的任何函数,但是仍然会出现如下错误:

  

'XXX'对象没有属性'operator'。

 class Math(object):
        "Main class to generate different math sums based on operator and difficulty levels"

        def __init__(self):
            self.operator = [
                addition,
                subtraction,
                multiplication,
                division
                ])

        def addition(self, a, b): return ('addition', '+', a+b)

        def subtraction(self, a, b): return ('subtraction', '-', a-c)

        def mutliplication(self, a, b): return ('multiplication', '*', a*c)

        def division(self, a, b): return ('division', '/', a/c)

        def mathsum(self, difficulty):
            """Function that generates random operator and math sum checks against your answer"""
            print self.operator

请帮忙

2 个答案:

答案 0 :(得分:2)

你错过了几个self.s:

def __init__(self):
    self.operator = [
        self.addition,
        self.subtraction,
        self.multiplication,
        self.division
        ]

另请注意,您在函数定义中拼错了乘法

答案 1 :(得分:0)

有了这个:

class MyMath(object):
    """Main class to generate different math sums based on operator and difficulty levels"""

    def __init__(self):
        self.operator = [ self.addition, self.subtraction, self.multiplication, self.division ]

    def addition(self, a, b):
        return ('addition', '+', a+b)

    def subtraction(self, a, b):
        return ('subtraction', '-', a-b)

    def multiplication(self, a, b):
        return ('multiplication', '*', a*b)

    def division(self, a, b):
        return ('division', '/', a/b)

    def mathsum(self, difficulty, a, b):
        """Function that generates random operator and math sum checks against your answer"""
        print self.operator

致电:

MyMath().addition(2, 3)

给出这个:

('addition', '+', 5)

我不确定您在调用序列和结果方面的期望是什么,但如果声明并按上述方式调用,则不会产生错误。