1

我正在尝试定义一个将 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)

好像我错过了一些非常基本的东西,任何帮助将不胜感激。

4

2 回答 2

6

如果您想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

于 2013-10-27T04:55:38.107 回答
2

只是改变:

def test_method(par1, par2):

def test_method(self, par1, par2):
于 2013-10-27T04:52:17.420 回答