首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python语言中,调用类方法会引发TypeError

在Python语言中,调用类方法会引发TypeError
EN

Stack Overflow用户
提问于 2008-12-28 23:36:47
回答 6查看 143.9K关注 0票数 71

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

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)

怎么了?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2008-12-28 23:48:05

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

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

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

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

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

票数 88
EN

Stack Overflow用户

发布于 2008-12-28 23:51:21

从您的示例来看,在我看来您想要使用静态方法。

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中大量使用静态方法通常是某种恶臭的症状-如果你真的需要函数,那么直接在模块级声明它们。

票数 34
EN

Stack Overflow用户

发布于 2014-05-24 10:51:05

要对示例进行最小程度的修改,您可以将代码修改为:

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()
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/396856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档