【问题标题】:Error in when Python Class makePython 类生成时出错
【发布时间】:2018-07-25 02:41:37
【问题描述】:

代码:

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(最近一次调用最后一次):文件“calculator.py”,第 19 行,在 calculator.division(100,4) TypeError: unbound method division() must be called withcalculator instance as first argument (got int 而是实例)

我正在学习 Python,所以任何人都可以解决这个错误。

【问题讨论】:

标签: python


【解决方案1】:

您可以使用@staticmethod 将您的函数设为静态(这样您就可以在不创建实例的情况下调用它们)

class Calculator:
    @staticmethod
    def addition(x, y):
        add = x + y
        print(add)

Calculator.addition(10, 3)

或者您添加self 作为参数并创建Calculator 的实例。

class Calculator:
    def addition(self, x, y):
        add = x + y
        print(add)

calc = Calculator()
calc.addition(10, 3)

【讨论】:

    【解决方案2】:

    您的代码存在一些问题。首先,您创建了一个类,但您从不实例化该类的实例。如:

    class Calculator:
        ...
        ...
    
    calculator = Calculator()
    

    其次,从对象调用的方法总是接受对象本身作为第一个参数。这就是为什么你在方法的定义中看到self。即使你不使用self,它仍然作为第一个参数隐式传递。

    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()
    

    【讨论】:

    • 没问题。请将问题标记为已回答(复选标记)
    猜你喜欢
    • 2020-05-08
    • 1970-01-01
    • 2013-10-21
    • 2012-01-21
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多