可能重复:
在python中获取方法参数名称
有没有一种简单的方法可以在python函数中获取参数名称列表?
例如:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Run Code Online (Sandbox Code Playgroud)
谢谢
鉴于Python函数:
def a_method(arg1, arg2):
pass
Run Code Online (Sandbox Code Playgroud)
如何提取参数的数量和名称.即,鉴于我有一个func的引用,我想要返回func.[something]("arg1","arg2").
这种情况的使用场景是我有一个装饰器,我希望使用方法参数的顺序与它们为实际函数出现的顺序相同.也就是说,当我调用aMethod("a","b")时,装饰器看起来会打印出"a,b"吗?
如何将参数名称及其值作为字典传递给方法?
我想为GET请求指定可选和必需的参数作为HTTP API的一部分,以便构建URL.我不确定制作这种pythonic的最佳方法.
我梦想着一个带有显式关键字args的Python方法:
def func(a=None, b=None, c=None):
for arg, val in magic_arg_dict.items(): # Where do I get the magic?
print '%s: %s' % (arg, val)
Run Code Online (Sandbox Code Playgroud)
我想得到一个字典,只有调用者实际传入方法的那些参数,就像**kwargs,但我不希望调用者能够传递任何旧的随机args,不像**kwargs.
>>> func(b=2)
b: 2
>>> func(a=3, c=5)
a: 3
c: 5
Run Code Online (Sandbox Code Playgroud)
所以:有这样的咒语吗?在我的情况下,我碰巧能够将每个参数与其默认值进行比较以找到不同的参数,但是当你有九个参数时,这有点不雅并且变得单调乏味.对于奖励积分,提供一个咒语,即使调用者传递了一个分配了默认值的关键字参数,也可以告诉我:
>>> func(a=None)
a: None
Run Code Online (Sandbox Code Playgroud)
调皮!
编辑:(词法)函数签名必须保持不变.它是公共API的一部分,显式关键字args的主要价值在于它们的文档值.只是为了让事情变得有趣.:)
给定一个Enum无法修改的对象,以及一个自定义Query类,该类应该生成Enum给定不同参数的值的编译:
from enum import Enum
class Fields(Enum):
a = ["hello", "world"]
b = ["foo", "bar", "sheep"]
c = ["what", "the"]
d = ["vrai", "ment", "cest", "vrai"]
e = ["foofoo"]
class Query:
def __init__(self, a=True, b=True, c=False, d=False, e=False):
self.query_fields = set()
self.query_fields.update(Fields.a.value) if a else None
self.query_fields.update(Fields.b.value) if b else None
self.query_fields.update(Fields.c.value) if c else None
self.query_fields.update(Fields.d.value) if d else None
self.query_fields.update(Fields.e.value) if e else None
Run Code Online (Sandbox Code Playgroud)
可以获得一组自定义的query_fields,例如:
[出去]:
>>> x = Query() …Run Code Online (Sandbox Code Playgroud) 给定以下函数:
def test(* p1=None, p2=None):
...
Run Code Online (Sandbox Code Playgroud)
调用方式如下:
test(p2="hello")
Run Code Online (Sandbox Code Playgroud)
我可以在运行时以编程方式获取参数及其值的列表/字典吗?
1:不想使用,**kwargs因为我想强制用户使用正确的参数名称(并计划进行类型注释)。
2:我查看了inspect获取默认值的模块,但似乎没有让我看到运行时值。
想要创建类似这样的代码:
request = {k: v for k,v in __some_magic_location__ if v is not None}
Run Code Online (Sandbox Code Playgroud) 我有一个函数clans(),它接受 8 个参数。如果参数不是,我需要将键和值对添加到字典中None。我的解决方案是:
def clans(self, name: str = None, warFrequency: str = None, location: str = None,
minMembers: int = None, maxMembers: int = None,
minClanPoints: int = None, minClanLevel: int = None,
labels: list[str] = None):
params = {} # <- the dictionary to add to
# very much if-conditions
if name is not None:
params['name'] = name
if warFrequency is not None:
params['warFrequency'] = warFrequency
... # <- other function arguments and if conditions …Run Code Online (Sandbox Code Playgroud) python ×7
arguments ×2
dictionary ×2
python-3.x ×2
class ×1
decorator ×1
enums ×1
if-statement ×1
keyword ×1
nonetype ×1
object ×1
parameters ×1
set ×1