Python如何调用自定义类中的函数?

lass learnclass:
def classadd(a,b):
return a+b

>>> learnclass.classadd(1,2)

Traceback (most recent call last):
File "<pyshell#88>", line 1, in <module>
learnclass.classadd(1,2)
TypeError: unbound method classadd() must be called with learnclass instance as first argument (got int instance instead)

为什么会出现错误

第1个回答  2015-06-06
定义一个函数只给了函数一个名称,指定了函数里包含的参数,和代码块结构。这个函数的基本结构完成以后,你可以通过另一个函数调用执行,也可以直接从Python提示符执行。

如下实例调用了printme()函数:

复制代码 代码如下:#!/usr/bin/python

# Function definition is here
def printme( str ):
"打印任何传入的字符串"
print str;
return;

# Now you can call printme function
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");
#以上实例输出结果:

#我要调用用户自定义函数!
#再次调用同一函数
第2个回答  2014-05-09
你好:
你要在自定义的函数里面的第一个参数设置为:
self
这是python约定的;
调用的时候可以不用管它,它相当于this!本回答被提问者和网友采纳
相似回答