当前位置:  开发笔记 > 编程语言 > 正文

调用类方法会在Python中引发TypeError

如何解决《调用类方法会在Python中引发TypeError》经验,为你挑选了3个好方法。

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

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 
    print(MyStuff.average(9, 18, 27))
TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead)

怎么了?



1> 小智..:

您可以通过声明变量并将类调用为实例来实例化该类:

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

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

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

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


@JoshSmeaton你应该真的使用"self",因为即使它不是技术上要求的,它也是一个非常标准的约定,并且会使你的代码成为其他python开发人员的主流.
你可以随意调用它."自我"只是一种惯例.

2> rob..:

从您的示例中,我觉得您想要使用静态方法.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

请注意,在python中大量使用静态方法通常是一些难闻气味的症状 - 如果你真的需要函数,那么直接在模块级别声明它们.


另一方面,python中"self"的显式用法和静态方法的错误信念对于来自其他语言的人来说是一个常见的陷阱.由于这里有许多指向文档和资源,我认为至少应该有一个"直接"的回复.谢谢你的评论!
对不起,我想你错误解释了这个问题.似乎stu对Python来说是新手,因此将他引导到Python基础知识的良好资源可能比向他展示如何使用静态方法更好;)

3> cmoman..:

要最低限度地修改您的示例,您可以将代码修改为:

class myclass(object):
        def __init__(self): # this method creates the class object.
                pass

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


mystuff=myclass()  # by default the __init__ method is then called.      
print mystuff.average(a,b,c)

或者更全面地扩展它,允许您添加其他方法.

class myclass(object):
        def __init__(self,a,b,c):
                self.a=a
                self.b=b
                self.c=c
        def average(self): #get the average of three numbers
                result=self.a+self.b+self.c
                result=result/3
                return result

a=9
b=18
c=27
mystuff=myclass(a, b, c)        
print mystuff.average()

推荐阅读
重庆制造漫画社
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有