stu*_*stu 71 python methods class python-3.x
我不明白如何使用类.当我尝试使用该类时,以下代码给出了一个错误.
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))
Run Code Online (Sandbox Code Playgroud)
错误:
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)
Run Code Online (Sandbox Code Playgroud)
怎么了?
小智 87
您可以通过声明变量并将类调用为实例来实例化该类:
x = mystuff()
print x.average(9,18,27)
Run Code Online (Sandbox Code Playgroud)
但是,这不适用于您提供给我们的代码.在给定对象(x)上调用类方法时,它总是在调用函数时将指向对象的指针作为第一个参数传递.因此,如果您现在运行代码,您将看到以下错误消息:
TypeError: average() takes exactly 3 arguments (4 given)
Run Code Online (Sandbox Code Playgroud)
要解决此问题,您需要修改平均方法的定义以获取四个参数.第一个参数是对象引用,其余3个参数是3个数字.
rob*_*rob 34
从您的示例中,我觉得您想要使用静态方法.
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)
Run Code Online (Sandbox Code Playgroud)
请注意,在python中大量使用静态方法通常是一些难闻气味的症状 - 如果你真的需要函数,那么直接在模块级别声明它们.
cmo*_*man 13
要最低限度地修改您的示例,您可以将代码修改为:
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)
Run Code Online (Sandbox Code Playgroud)
或者更全面地扩展它,允许您添加其他方法.
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142681 次 |
| 最近记录: |