我不明白如何使用类.当我尝试使用该类时,以下代码给出了一个错误.
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, inprint(MyStuff.average(9, 18, 27)) TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead)
怎么了?
您可以通过声明变量并将类调用为实例来实例化该类:
x = mystuff() print x.average(9,18,27)
但是,这不适用于您提供给我们的代码.在给定对象(x)上调用类方法时,它总是在调用函数时将指向对象的指针作为第一个参数传递.因此,如果您现在运行代码,您将看到以下错误消息:
TypeError: average() takes exactly 3 arguments (4 given)
要解决此问题,您需要修改平均方法的定义以获取四个参数.第一个参数是对象引用,其余3个参数是3个数字.
从您的示例中,我觉得您想要使用静态方法.
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中大量使用静态方法通常是一些难闻气味的症状 - 如果你真的需要函数,那么直接在模块级别声明它们.
要最低限度地修改您的示例,您可以将代码修改为:
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()