【问题标题】:How do you pass a list as an argument to a method如何将列表作为参数传递给方法
【发布时间】:2013-11-06 00:58:15
【问题描述】:

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

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

【问题讨论】:

  • 你没有将 self 传递给test_method
  • 更改为def test_method(self, par1, par2)。方法的第一个参数always 引用实例(通常命名为“self”)。
  • 类中定义的任何方法的第一个参数应该是一个对象,通常是self

标签: python list class methods parameters


【解决方案1】:

如果您希望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

【讨论】:

  • 所以问题与我提交列表作为参数这一事实无关,任何其他参数类型都会发生这种情况。我会说,该错误消息并不是那么有帮助。谢谢,现在我知道如何以及为什么了。
  • @user2923409 消息模棱两可的原因是因为“self”实际上不是 Python 中的关键字,它只是一个基本上每个人都使用的约定(如果你不要使用自我)。因此,它没有告诉您在标题中遗漏了“self”,而是说您向函数传递了三个参数(self、par1、par2)而不是预期的两个参数(par1、par2)。它真的无话可说……很高兴我能帮上忙。
  • @user2923409 现在,假设您输入了一个整数并将其存储在self.number 中。如果您随后在 myClass 中有一个方法将 self.number 视为 list 并使用 for 循环遍历它,那么如果您尝试运行所述方法,您将收到错误消息,指出 self.number 不是可迭代。
【解决方案2】:

只是改变:

def test_method(par1, par2):

def test_method(self, par1, par2):

【讨论】: