简体   繁体   English

Python:将字典变量作为 function 参数传递

[英]Python: pass dictionary variable as function argument

I am reusing a piece of code from another developer (it is a socket listener) which has the following function:我正在重用另一位开发人员的一段代码(它是一个套接字侦听器),它具有以下 function:

def start_my_client(self, *, config: dict):

I am new to Python, so I am assuming it requires a dictionary variable to be passed as an argument, so I created this variable:我是 Python 的新手,所以我假设它需要一个字典变量作为参数传递,所以我创建了这个变量:

config_dic = {'name': 'my_socket', 'hostname': 'test', 'description': 'TEST'}

However, I tried many different ways to pass the variable when calling the function, but none of them worked for me, for example:但是,我在调用 function 时尝试了很多不同的方法来传递变量,但没有一种对我有用,例如:

def handle_messages(conn, addr):
    conn.start_my_client(config=config_dic)

I receive nothing from the function. I tried this too:我没有收到来自 function 的任何信息。我也试过这个:

def handle_messages(conn, addr):
    conn.start_my_client(**config_dic)

It throws this error:它抛出这个错误:

TypeError: start_my_client() got an unexpected keyword argument 'name'

Any hint on how to pass the variable?关于如何传递变量的任何提示?

The first call looks reasonable第一个电话看起来很合理

def handle_messages(conn, addr):
    conn.start_my_client(config=config_dic)

What is expected output for this? output 对此有何期待?

If you pass config_dic like that如果你像那样传递 config_dic

def handle_messages(conn, addr):
    conn.start_my_client(**config_dic)

you perform unpacking arguments here.你在这里执行解包 arguments。 This means that the method start_my_client get arguments the same way as if you would call method like that这意味着方法 start_my_client 获取 arguments 的方式与您调用这样的方法的方式相同

conn.start_my_client(name='my_socket', hostname='test', description='TEST')

This is the reason you got error这就是你出错的原因

TypeError: start_my_client() got an unexpected keyword argument 'name'

start_my_client doesnt expect argument called name. start_my_client 不期望名为 name 的参数。

As mentioned in:如中所述:

What does ** (double star/asterisk) and * (star/asterisk) do for parameters? **(双星/星号)和 *(星号/星号)对参数有何作用?

the function you are using can receive several different arguments:你使用的function可以收到几个不同的arguments:

def start_my_client(self, *, config: dict):

So, it could take a number of arguments when called, something like this:因此,调用时可能需要一个数字 arguments,如下所示:

conn.start_my_client(a, b, c)

As for the : , this至于: ,这个

Function parameter with colon Function 带冒号的参数

Just indicate that each of the parameters passed should be dicts .只需指出传递的每个参数都应该是dicts

So, you could just call the function as:因此,您可以将 function 称为:

def handle_messages(conn, addr):
    conn.start_my_client(config_dic)

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

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