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

查看:75
本文介绍了调用类方法会在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天全站免登陆