Python类和方法实例化

时间:2016-06-05 05:23:19

标签: python class

这是我的代码:

class calculator:

    def addition(x,y):
        added=x+y
        print(added)

    def subtraction(x,y):
        sub=x-y
        print(sub)

    def multiplication(x,y):
        mult=x*y
        print(mult)

    def division(x,y):
        div= x/y
        print(div)

calculator.addition(5,7)

该程序给出了以下错误:

Traceback (most recent call last):
  File "C:/Python27/docs/defin_class.py", line 21, in <module>
    calculator.addition(6,3)
TypeError: unbound method addition() must be called with calculator instance as first argument (got int instance instead)

我不明白这个错误。请帮忙。

1 个答案:

答案 0 :(得分:1)

因此,如果不进一步了解细节,你应该在每个函数上面添加@staticmethod装饰器,就像我在下面所做的那样:

class calculator:

    @staticmethod
    def addition(x,y):
        added=x+y
        print(added)

    @staticmethod
    def subtraction(x,y):
        sub=x-y
        print(sub)

    @staticmethod
    def multiplication(x,y):
        mult=x*y
        print(mult)

    @staticmethod
    def division(x,y):
        div= x/y
        print(div)

calculator.addition(5,7)

原因是所有这些方法都是计算器的功能,但它们不能在计算器类的对象上运行。

为了全面了解您应该在Python中使用的不同类型的方法,我强烈推荐this blog post。祝你好运!