如何将字典传递给python中的函数?
我试图将字典传递给python中的函数,但它显示了错误如何将字典传递给python中的函数?,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我试图将字典传递给python中的函数,但它显示了错误 class stud: def method(**arg): print(arg) dict1 = {1:"abc",2:"xyz"} a = stud() a.method(dict1) 这会引发以下错误: >>> a.method(dict1) Traceback (most recent call last): File "<st
class stud:
def method(**arg):
print(arg)
dict1 = {1:"abc",2:"xyz"}
a = stud()
a.method(dict1)
这会引发以下错误:
>>> a.method(dict1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes 0 positional arguments but 2 were given
>a.method(dict1)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:method()接受0个位置参数,但提供了2个
你能告诉我我是错了还是把字典传给函数的正确方法吗?正如@Bit提到的,如果
方法
不是静态方法。您需要添加一个self
参数
这里有两个选项:
- 在方法中使用正常参数:
class螺柱:
def方法(self,arg):#正常参数
打印(arg)
- 在调用中将字典作为命名参数传递:
class螺柱:
def方法(自身,**参数):#正常参数
打印(arg)
a、 方法(**dict1)
就我个人而言,我会选择第一个,因为它是:
method
的签名不包括self
,这不是问题吗?@Bit:很好,我忽略了这一点。@Digres:当然你应该包括3.5以上的签名。数据模型没有改变。仅对于静态方法(对于类方法,cls
),没有self.ok谢谢我现在就得到了@WillemVanOnsem
class stud:
def method(self,arg): # normal parameter
print(arg)
class stud:
def method(self,**arg): # normal parameter
print(arg)
a.method(**dict1)