Error in when Python Class make
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class calculator: def addition(x,y): add = x + y print (add) def subtraction(x,y): sub = x - y print (sub) def multiplication(x,y): mul = x * y print (mul) def division(x,y): div = x / y print (div) calculator.division(100,4) calculator.multiplication(22,4) calculator.subtraction(20,2) calculator.addition(10,3) |
当我运行此代码时,出现错误:
Traceback (most recent call last): File"calculator.py", line 19, in
calculator.division(100,4) TypeError: unbound method division() must be called with calculator instance as first argument (got int
instance instead)
我正在学习python,所以任何人都能解决这个错误。
您可以使用
1 2 3 4 5 6 7 | class Calculator: @staticmethod def addition(x, y): add = x + y print(add) Calculator.addition(10, 3) |
或者添加
1 2 3 4 5 6 7 | class Calculator: def addition(self, x, y): add = x + y print(add) calc = Calculator() calc.addition(10, 3) |
您的代码有几个问题。首先,创建一个类,但从未实例化该类的实例。例如:
1 2 3 4 5 | class Calculator: ... ... calculator = Calculator() |
其次,从对象调用的方法总是接受对象本身作为第一个参数。这就是为什么你在方法的定义中看到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Calculator: def addition(self, x, y): add = x + y print(add) def subtraction(self, x, y): sub = x - y print(sub) def multiplication(self, x, y): mul = x * y print(mul) def division(self, x, y): div = x / y print(div) calculator = Calculator() |