在 Python 中调用类方法会引发 TypeError [英] Calling a class method raises a TypeError in Python

查看:23
本文介绍了在 Python 中调用类方法会引发 TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白类是如何使用的.当我尝试使用该类时,以下代码给了我一个错误.

I don't understand how classes are used. The following code gives me an error when I try to use the class.

class MyStuff:
    def average(a, b, c): # Get the average of three numbers
        result = a + b + c
        result = result / 3
        return result

# Now use the function `average` from the `MyStuff` class
print(MyStuff.average(9, 18, 27))

错误:

File "class.py", line 7, in <module>
    print(MyStuff.average(9, 18, 27))
TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead)

怎么了?

推荐答案

您可以通过声明一个变量并像调用函数一样调用类来实例化类:

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

但是,这不适用于您提供给我们的代码.当您在给定的对象 (x) 上调用类方法时,它总是在调用函数时将指向该对象的指针作为第一个参数传递.所以如果你现在运行你的代码,你会看到这个错误信息:

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

要解决此问题,您需要修改平均值方法的定义以采用四个参数.第一个参数是一个对象引用,剩下的3个参数是3个数字.

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

这篇关于在 Python 中调用类方法会引发 TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆