简体   繁体   English

将List作为参数传递给另一个方法,但是该方法在Python中将该参数接受为Tuple吗?

[英]Passing List as an argument to another method, but the method accept the parameter as Tuple in Python?

I am passing a List as an argument to another method. 我将列表作为参数传递给另一种方法。 But the method accepting the parameter as Tuple. 但是接受参数为Tuple的方法。

class A():
   def method(self):
      lst = [{'CITY': 'Boston', 'STATE': 'MA'},
           {'CITY': 'New York', 'STATE': 'NY'}]
      self.method1(self,*lst)

   def method1(self,*param):
      print(type(param))
      print(param)

b =A()
b.method() # Printing type as Tuple

I want to get the List not the Tuple. 我想获取列表而不是元组。 Any suggestion! 有任何建议!

When you do *lst , you're unpacking the contents of lst as arguments to the function method1 . 当您执行*lst ,您要解lst的内容作为方法method1参数。 The function method1 is actually taking multiple args because you've done *param - it takes as many parameters as you pass it. 函数method1实际上需要多个args,因为您已经完成了*param它接受与传递一样多的参数。

When you unpack lst and pass it to method1 , it takes it in as a tuple by definition. 当您解压缩lst并将其传递给method1 ,根据定义,它会将其作为一个元组接收。

Observe: 注意:

>>> L = ['hi', 'hello']
>>> def A(*args):
...     print(args)
... 
>>> A(*L)
('hi', 'hello')

To fix your issue, remove both your asterisks and take in a list object - don't unpack your list. 要解决您的问题,请同时删除两个星号并放入一个list对象-不要打开列表的包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM