我正在尝试定义一种方法,它将 python 列表作为其输入参数之一。相比之下,常规函数可以毫无问题地接受列表作为输入参数。怎么会?
# Simple function that works
def func(param1, param2):
for item in param1:
print item+" "+param2
var1 = ['sjd', 'jkfgljf', 'poipopo', 'uyuyuyu']
var2 = 'is nonsense'
func(var1, var2)
# Simple function produces the following output:
# sjd is nonsense
# jkfgljf is nonsense
# poipopo is nonsense
# uyuyuyu is nonsense
如果我尝试使用类中的方法获得类似的效果,如下所示:
# Simple class
class test():
def __init__(self):
pass
def test_method(par1, par2):
for itm in par1:
print itm+" "+par2
# This executes with no error
obj = test()
# This fails
obj.test_method(var1, var2)
# Error message will be:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: test_method() takes exactly 2 arguments (3 given)
似乎我遗漏了一些非常基本的东西,我们将不胜感激任何帮助。
请您参考如下方法:
如果您希望test_method 能够访问您类中的数据成员,那么您需要传递self,如:
def test_method(self, par1, par2):
如果 test_method 不需要访问类中的数据成员,则将其声明为静态方法:
@staticmethod
def test_method(par1, par2):
作为引用,假设你有一个包含数字的类,你想在一个方法中返回该数字,你有另一个方法给出两个数字的乘积,但不依赖于你的类中的任何东西.以下是您的操作方式:
class myClass(object):
def __init__(self, num):
self.number = num
def getNum(self):
return self.number
@staticmethod
def product(num1,num2):
return num1*num2
if __name__ == "__main__":
obj = myClass(4)
print obj.getNum()
print myClass.product(2,3)
打印:
4
6
