标签归档:arguments

如何在Tkinter中将参数传递给Button命令?

问题:如何在Tkinter中将参数传递给Button命令?

假设我Button在Python中使用Tkinter进行了以下操作:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)

action当我按下按钮时会调用该方法,但是如果我想向该方法传递一些参数action呢?

我尝试使用以下代码:

button = Tk.Button(master=frame, text='press', command=action(someNumber))

这只是立即调用该方法,而按该按钮则没有任何作用。

Suppose I have the following Button made with Tkinter in Python:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)

The method action is called when I press the button, but what if I wanted to pass some arguments to the method action?

I have tried with the following code:

button = Tk.Button(master=frame, text='press', command=action(someNumber))

This just invokes the method immediately, and pressing the button does nothing.


回答 0

我个人更喜欢lambdas在这种情况下使用,因为imo更加简单明了,并且如果您无法控制被调用的方法,也不会强迫您编写很多包装方法,但这当然是一个问题。

这就是使用lambda的方式(请注意,在功能模块中还存在一些currying的实现,因此您也可以使用它):

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

I personally prefer to use lambdas in such a scenario, because imo it’s clearer and simpler and also doesn’t force you to write lots of wrapper methods if you don’t have control over the called method, but that’s certainly a matter of taste.

That’s how you’d do it with a lambda (note there’s also some implementation of currying in the functional module, so you can use that too):

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

回答 1

这也可以通过使用partial标准库functools来完成,如下所示:

from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)

This can also be done by using partial from the standard library functools, like this:

from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)

回答 2

GUI示例:

假设我有GUI:

import tkinter as tk

root = tk.Tk()

btn = tk.Button(root, text="Press")
btn.pack()

root.mainloop()

按下按钮时会发生什么

看到btn按下时它会调用自己的函数,函数与button_press_handle以下示例非常相似:

def button_press_handle(callback=None):
    if callback:
        callback() # Where exactly the method assigned to btn['command'] is being callled

与:

button_press_handle(btn['command'])

您可以简单地认为command应该将option设置为对我们要调用的方法的引用,类似于callbackin button_press_handle


按下按钮时调用方法(回调

没有参数

因此,如果要在print按下按钮时进行某些操作,则需要进行以下设置:

btn['command'] = print # default to print is new line

请密切注意缺少()print方法的不足,该方法的含义是:“这是我要在按下时调用的方法名称,不要立即调用。” 但是,我没有为传递任何参数,print因此在没有参数的情况下,它会打印任何内容。

论点

现在,如果我还希望将参数传递给要在按下按钮时调用的方法,则可以使用匿名函数,该函数可以通过lambda语句创建,在这种情况下,将使用print内置方法,如下所示:

btn['command'] = lambda arg1="Hello", arg2=" ", arg3="World!" : print(arg1 + arg2 + arg3)

按下按钮时调用多种方法

没有参数

您也可以使用using lambda语句实现该功能,但是这被认为是不好的做法,因此在此不再赘述。好的做法是定义一个单独的方法,multiple_methods该方法调用所需的方法,然后将其设置为按下按钮的回调:

def multiple_methods():
    print("Vicariously") # the first inner callback
    print("I") # another inner callback

论点

为了将参数传递给调用其他方法的方法,请再次使用lambda语句,但首先:

def multiple_methods(*args, **kwargs):
    print(args[0]) # the first inner callback
    print(kwargs['opt1']) # another inner callback

然后设置:

btn['command'] = lambda arg="live", kw="as the" : a_new_method(arg, opt1=kw)

从回调返回对象

还要进一步注意,这callback并不是真的,return因为它仅在button_press_handlewith 内调用,callback()而不是return callback()。确实return不在该功能之外的任何地方。因此,您应该修改当前作用域中可访问的对象。


具有全局对象修改的完整示例

下面的示例将调用一个方法,该方法btn每次按下按钮都会更改的文本:

import tkinter as tk

i = 0
def text_mod():
    global i, btn           # btn can be omitted but not sure if should be
    txt = ("Vicariously", "I", "live", "as", "the", "whole", "world", "dies")
    btn['text'] = txt[i]    # the global object that is modified
    i = (i + 1) % len(txt)  # another global object that gets modified

root = tk.Tk()

btn = tk.Button(root, text="My Button")
btn['command'] = text_mod

btn.pack(fill='both', expand=True)

root.mainloop()

镜子

Example GUI:

Let’s say I have the GUI:

import tkinter as tk

root = tk.Tk()

btn = tk.Button(root, text="Press")
btn.pack()

root.mainloop()

What Happens When a Button Is Pressed

See that when btn is pressed it calls its own function which is very similar to button_press_handle in the following example:

def button_press_handle(callback=None):
    if callback:
        callback() # Where exactly the method assigned to btn['command'] is being callled

with:

button_press_handle(btn['command'])

You can simply think that command option should be set as, the reference to the method we want to be called, similar to callback in button_press_handle.


Calling a Method(Callback) When the Button is Pressed

Without arguments

So if I wanted to print something when the button is pressed I would need to set:

btn['command'] = print # default to print is new line

Pay close attention to the lack of () with the print method which is omitted in the meaning that: “This is the method’s name which I want you to call when pressed but don’t call it just this very instant.” However, I didn’t pass any arguments for the print so it printed whatever it prints when called without arguments.

With Argument(s)

Now If I wanted to also pass arguments to the method I want to be called when the button is pressed I could make use of the anonymous functions, which can be created with lambda statement, in this case for print built-in method, like the following:

btn['command'] = lambda arg1="Hello", arg2=" ", arg3="World!" : print(arg1 + arg2 + arg3)

Calling Multiple Methods when the Button Is Pressed

Without Arguments

You can also achieve that using lambda statement but it is considered bad practice and thus I won’t include it here. The good practice is to define a separate method, multiple_methods, that calls the methods wanted and then set it as the callback to the button press:

def multiple_methods():
    print("Vicariously") # the first inner callback
    print("I") # another inner callback

With Argument(s)

In order to pass argument(s) to method that calls other methods, again make use of lambda statement, but first:

def multiple_methods(*args, **kwargs):
    print(args[0]) # the first inner callback
    print(kwargs['opt1']) # another inner callback

and then set:

btn['command'] = lambda arg="live", kw="as the" : a_new_method(arg, opt1=kw)

Returning Object(s) From the Callback

Also further note that callback can’t really return because it’s only called inside button_press_handle with callback() as opposed to return callback(). It does return but not anywhere outside that function. Thus you should rather modify object(s) that are accessible in the current scope.


Complete Example with global Object Modification(s)

Below example will call a method that changes btn‘s text each time the button is pressed:

import tkinter as tk

i = 0
def text_mod():
    global i, btn           # btn can be omitted but not sure if should be
    txt = ("Vicariously", "I", "live", "as", "the", "whole", "world", "dies")
    btn['text'] = txt[i]    # the global object that is modified
    i = (i + 1) % len(txt)  # another global object that gets modified

root = tk.Tk()

btn = tk.Button(root, text="My Button")
btn['command'] = text_mod

btn.pack(fill='both', expand=True)

root.mainloop()

Mirror


回答 3

Python提供函数参数默认值的能力为我们提供了一条出路。

def fce(x=myX, y=myY):
    myFunction(x,y)
button = Tk.Button(mainWin, text='press', command=fce)

请参阅:http : //infohost.nmt.edu/tcc/help/pubs/tkinter/web/extra-args.html

对于更多按钮,您可以创建一个返回函数的函数:

def fce(myX, myY):
    def wrapper(x=myX, y=myY):
        pass
        pass
        pass
        return x+y
    return wrapper

button1 = Tk.Button(mainWin, text='press 1', command=fce(1,2))
button2 = Tk.Button(mainWin, text='press 2', command=fce(3,4))
button3 = Tk.Button(mainWin, text='press 3', command=fce(9,8))

Python’s ability to provide default values for function arguments gives us a way out.

def fce(x=myX, y=myY):
    myFunction(x,y)
button = Tk.Button(mainWin, text='press', command=fce)

See: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/extra-args.html

For more buttons you can create a function which returns a function:

def fce(myX, myY):
    def wrapper(x=myX, y=myY):
        pass
        pass
        pass
        return x+y
    return wrapper

button1 = Tk.Button(mainWin, text='press 1', command=fce(1,2))
button2 = Tk.Button(mainWin, text='press 2', command=fce(3,4))
button3 = Tk.Button(mainWin, text='press 3', command=fce(9,8))

回答 4

建立在Matt Thompsons的答案上:可以将一个类设为可调用的,因此可以代替一个函数来使用它:

import tkinter as tk

class Callback:
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs
    def __call__(self):
        self.func(*self.args, **self.kwargs)

def default_callback(t):
    print("Button '{}' pressed.".format(t))

root = tk.Tk()

buttons = ["A", "B", "C"]

for i, b in enumerate(buttons):
    tk.Button(root, text=b, command=Callback(default_callback, b)).grid(row=i, column=0)

tk.mainloop()

Building on Matt Thompsons answer : a class can be made callable so it can be used instead of a function:

import tkinter as tk

class Callback:
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs
    def __call__(self):
        self.func(*self.args, **self.kwargs)

def default_callback(t):
    print("Button '{}' pressed.".format(t))

root = tk.Tk()

buttons = ["A", "B", "C"]

for i, b in enumerate(buttons):
    tk.Button(root, text=b, command=Callback(default_callback, b)).grid(row=i, column=0)

tk.mainloop()

回答 5

它立即调用该方法并且按下按钮没有执行任何操作的原因action(somenumber)是已评估并且其返回值归因于按钮的命令。因此,如果action打印出一些东西告诉您它已经运行并返回了None,那么您只需运行action以评估其返回值并给出None作为按钮的命令。

要使按钮具有不同的参数来调用函数,可以使用全局变量,尽管我不建议这样做:

import Tkinter as Tk

frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
frame.grid(row=2,column=2)
frame.pack(fill=Tk.X, padx=5, pady=5)
def action():
    global output
    global variable
    output.insert(Tk.END,variable.get())
button = Tk.Button(master=frame, text='press', command=action)
button.pack()
variable = Tk.Entry(master=frame)
variable.pack()
output = Tk.Text(master=frame)
output.pack()

if __name__ == '__main__':
    Tk.mainloop()

我要做的是制作一个class其对象包含所需的每个变量和根据需要更改它们的方法:

import Tkinter as Tk
class Window:
    def __init__(self):
        self.frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
        self.frame.grid(row=2,column=2)
        self.frame.pack(fill=Tk.X, padx=5, pady=5)

        self.button = Tk.Button(master=self.frame, text='press', command=self.action)
        self.button.pack()

        self.variable = Tk.Entry(master=self.frame)
        self.variable.pack()

        self.output = Tk.Text(master=self.frame)
        self.output.pack()

    def action(self):
        self.output.insert(Tk.END,self.variable.get())

if __name__ == '__main__':
    window = Window()
    Tk.mainloop()

The reason it invokes the method immediately and pressing the button does nothing is that action(somenumber) is evaluated and its return value is attributed as the command for the button. So if action prints something to tell you it has run and returns None, you just run action to evaluate its return value and given None as the command for the button.

To have buttons to call functions with different arguments you can use global variables, although I can’t recommend it:

import Tkinter as Tk

frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
frame.grid(row=2,column=2)
frame.pack(fill=Tk.X, padx=5, pady=5)
def action():
    global output
    global variable
    output.insert(Tk.END,variable.get())
button = Tk.Button(master=frame, text='press', command=action)
button.pack()
variable = Tk.Entry(master=frame)
variable.pack()
output = Tk.Text(master=frame)
output.pack()

if __name__ == '__main__':
    Tk.mainloop()

What I would do is make a class whose objects would contain every variable required and methods to change those as needed:

import Tkinter as Tk
class Window:
    def __init__(self):
        self.frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
        self.frame.grid(row=2,column=2)
        self.frame.pack(fill=Tk.X, padx=5, pady=5)

        self.button = Tk.Button(master=self.frame, text='press', command=self.action)
        self.button.pack()

        self.variable = Tk.Entry(master=self.frame)
        self.variable.pack()

        self.output = Tk.Text(master=self.frame)
        self.output.pack()

    def action(self):
        self.output.insert(Tk.END,self.variable.get())

if __name__ == '__main__':
    window = Window()
    Tk.mainloop()

回答 6

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

我相信应该解决这个问题

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

I believe should fix this


回答 7

最好的做法是使用lambda,如下所示:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

The best thing to do is use lambda as follows:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

回答 8

我来晚了,但是这是完成它的一种非常简单的方法。

import tkinter as tk
def function1(param1, param2):
    print(str(param1) + str(param2))

var1 = "Hello "
var2 = "World!"
def function2():
    function1(var1, var2)

root = tk.Tk()

myButton = tk.Button(root, text="Button", command=function2)
root.mainloop()

您只需将要使用的功能包装到另一个功能中,然后在按下按钮时调用第二个功能。

I am extremely late, but here is a very simple way of accomplishing it.

import tkinter as tk
def function1(param1, param2):
    print(str(param1) + str(param2))

var1 = "Hello "
var2 = "World!"
def function2():
    function1(var1, var2)

root = tk.Tk()

myButton = tk.Button(root, text="Button", command=function2)
root.mainloop()

You simply wrap the function you want to use in another function and call the second function on the button press.


回答 9

Lambda很不错,但是您也可以尝试一下(在for循环中顺便说一句):

root = Tk()

dct = {"1": [*args], "2": [*args]}
def keypress(event):
    *args = dct[event.char]
    for arg in args:
        pass
for i in range(10):
    root.bind(str(i), keypress)

之所以起作用,是因为设置了绑定后,按键将事件作为参数传递。然后,您可以取消事件的属性,例如event.char获得“ 1”或“ UP”。如果您需要一个或多个事件属性以外的参数。只需创建一个字典来存储它们。

Lambdas are all well and good, but you can also try this (which works in a for loop btw):

root = Tk()

dct = {"1": [*args], "2": [*args]}
def keypress(event):
    *args = dct[event.char]
    for arg in args:
        pass
for i in range(10):
    root.bind(str(i), keypress)

This works because when the binding is set, a key press passes the event as an argument. You can then call attributes off the event like event.char to get “1” or “UP” ect. If you need an argument or multiple arguments other than the event attributes. just create a dictionary to store them.


回答 10

我也曾经遇到过这个问题。您可以只使用lambda:

button = Tk.Button(master=frame, text='press',command=lambda: action(someNumber))

I have encountered this problem before, too. You can just use lambda:

button = Tk.Button(master=frame, text='press',command=lambda: action(someNumber))

回答 11

如果您要执行更多操作,请使用lambda将条目数据传递给命令函数,例如:

event1 = Entry(master)
button1 = Button(master, text="OK", command=lambda: test_event(event1.get()))

def test_event(event_text):
    if not event_text:
        print("Nothing entered")
    else:
        print(str(event_text))
        #  do stuff

这会将事件中的信息传递给按钮功能。可能有更多类似Python的方式编写此代码,但这对我有用。

Use a lambda to pass the entry data to the command function if you have more actions to carry out, like this (I’ve tried to make it generic, so just adapt):

event1 = Entry(master)
button1 = Button(master, text="OK", command=lambda: test_event(event1.get()))

def test_event(event_text):
    if not event_text:
        print("Nothing entered")
    else:
        print(str(event_text))
        #  do stuff

This will pass the information in the event to the button function. There may be more Pythonesque ways of writing this, but it works for me.


回答 12

JasonPy-一些事情…

如果您将一个按钮粘在一个循环中,它将一遍又一遍地创建…这可能不是您想要的。(也许是)…

它总是获得最后一个索引的原因是单击它们时运行的lambda事件-而不是程序启动时。我不确定100%在做什么,但也许尝试在完成后存储值,然后稍后使用lambda按钮调用它。

例如:(不使用此代码,仅作为示例)

for entry in stuff_that_is_happening:
    value_store[entry] = stuff_that_is_happening

那你可以说…

button... command: lambda: value_store[1]

希望这可以帮助!

JasonPy – a few things…

if you stick a button in a loop it will be created over and over and over again… which is probably not what you want. (maybe it is)…

The reason it always gets the last index is lambda events run when you click them – not when the program starts. I’m not sure 100% what you are doing but maybe try storing the value when it’s made then call it later with the lambda button.

eg: (don’t use this code, just an example)

for entry in stuff_that_is_happening:
    value_store[entry] = stuff_that_is_happening

then you can say….

button... command: lambda: value_store[1]

hope this helps!


回答 13

一种简单的方法是button使用lambda以下语法进行配置:

button['command'] = lambda arg1 = local_var1, arg2 = local_var2 : function(arg1, arg2)

One simple way would be to configure button with lambda like the following syntax:

button['command'] = lambda arg1 = local_var1, arg2 = local_var2 : function(arg1, arg2)

回答 14

为了后代:您也可以使用类来实现类似的目的。例如:

class Function_Wrapper():
    def __init__(self, x, y, z):
        self.x, self.y, self.z = x, y, z
    def func(self):
        return self.x + self.y + self.z # execute function

然后可以通过以下方式简单地创建按钮:

instance1 = Function_Wrapper(x, y, z)
button1  = Button(master, text = "press", command = instance1.func)

这种方法还允许您通过设置来更改函数参数instance1.x = 3

For posterity: you can also use classes to achieve something similar. For instance:

class Function_Wrapper():
    def __init__(self, x, y, z):
        self.x, self.y, self.z = x, y, z
    def func(self):
        return self.x + self.y + self.z # execute function

Button can then be simply created by:

instance1 = Function_Wrapper(x, y, z)
button1  = Button(master, text = "press", command = instance1.func)

This approach also allows you to change the function arguments by i.e. setting instance1.x = 3.


回答 15

您需要使用 lambda:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

You need to use lambda:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

回答 16

使用lambda

import tkinter as tk

root = tk.Tk()
def go(text):
    print(text)

b = tk.Button(root, text="Click", command=lambda: go("hello"))
b.pack()
root.mainloop()

输出:

hello

Use lambda

import tkinter as tk

root = tk.Tk()
def go(text):
    print(text)

b = tk.Button(root, text="Click", command=lambda: go("hello"))
b.pack()
root.mainloop()

output:

hello

如何读取包含默认参数值的函数签名?

问题:如何读取包含默认参数值的函数签名?

给定一个功能对象,如何获得其签名?例如,用于:

def myMethod(firt, second, third='something'):
    pass

我想得到"myMethod(firt, second, third='something')"

Given a function object, how can I get its signature? For example, for:

def myMethod(firt, second, third='something'):
    pass

I would like to get "myMethod(firt, second, third='something')".


回答 0

import inspect

def foo(a, b, x='blah'):
    pass

print(inspect.getargspec(foo))
# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',))

但是,请注意,inspect.getargspec()自Python 3.0开始不推荐使用。

Python 3.0–3.4建议inspect.getfullargspec()

Python 3.5+建议inspect.signature()

import inspect

def foo(a, b, x='blah'):
    pass

print(inspect.getargspec(foo))
# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',))

However, note that inspect.getargspec() is deprecated since Python 3.0.

Python 3.0–3.4 recommends inspect.getfullargspec().

Python 3.5+ recommends inspect.signature().


回答 1

可以说,找到函数签名的最简单方法是help(function)

>>> def function(arg1, arg2="foo", *args, **kwargs): pass
>>> help(function)
Help on function function in module __main__:

function(arg1, arg2='foo', *args, **kwargs)

另外,在Python 3中,将一个方法添加到inspect名为的模块中signature,该方法旨在表示可调用对象签名及其返回注释

>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'

>>> str(sig.parameters['b'])
'b:int'

>>> sig.parameters['b'].annotation
<class 'int'>

Arguably the easiest way to find the signature for a function would be help(function):

>>> def function(arg1, arg2="foo", *args, **kwargs): pass
>>> help(function)
Help on function function in module __main__:

function(arg1, arg2='foo', *args, **kwargs)

Also, in Python 3 a method was added to the inspect module called signature, which is designed to represent the signature of a callable object and its return annotation:

>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'

>>> str(sig.parameters['b'])
'b:int'

>>> sig.parameters['b'].annotation
<class 'int'>

回答 2

#! /usr/bin/env python

import inspect
from collections import namedtuple

DefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value')

def _get_default_arg(args, defaults, arg_index):
    """ Method that determines if an argument has default value or not,
    and if yes what is the default value for the argument

    :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
    :param defaults: array of default values, eg: (42, 'something')
    :param arg_index: index of the argument in the argument array for which,
    this function checks if a default value exists or not. And if default value
    exists it would return the default value. Example argument: 1
    :return: Tuple of whether there is a default or not, and if yes the default
    value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42)
    """
    if not defaults:
        return DefaultArgSpec(False, None)

    args_with_no_defaults = len(args) - len(defaults)

    if arg_index < args_with_no_defaults:
        return DefaultArgSpec(False, None)
    else:
        value = defaults[arg_index - args_with_no_defaults]
        if (type(value) is str):
            value = '"%s"' % value
        return DefaultArgSpec(True, value)

def get_method_sig(method):
    """ Given a function, it returns a string that pretty much looks how the
    function signature would be written in python.

    :param method: a python method
    :return: A string similar describing the pythong method signature.
    eg: "my_method(first_argArg, second_arg=42, third_arg='something')"
    """

    # The return value of ArgSpec is a bit weird, as the list of arguments and
    # list of defaults are returned in separate array.
    # eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],
    # varargs=None, keywords=None, defaults=(42, 'something'))
    argspec = inspect.getargspec(method)
    arg_index=0
    args = []

    # Use the args and defaults array returned by argspec and find out
    # which arguments has default
    for arg in argspec.args:
        default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)
        if default_arg.has_default:
            args.append("%s=%s" % (arg, default_arg.default_value))
        else:
            args.append(arg)
        arg_index += 1
    return "%s(%s)" % (method.__name__, ", ".join(args))


if __name__ == '__main__':
    def my_method(first_arg, second_arg=42, third_arg='something'):
        pass

    print get_method_sig(my_method)
    # my_method(first_argArg, second_arg=42, third_arg="something")
#! /usr/bin/env python

import inspect
from collections import namedtuple

DefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value')

def _get_default_arg(args, defaults, arg_index):
    """ Method that determines if an argument has default value or not,
    and if yes what is the default value for the argument

    :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']
    :param defaults: array of default values, eg: (42, 'something')
    :param arg_index: index of the argument in the argument array for which,
    this function checks if a default value exists or not. And if default value
    exists it would return the default value. Example argument: 1
    :return: Tuple of whether there is a default or not, and if yes the default
    value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42)
    """
    if not defaults:
        return DefaultArgSpec(False, None)

    args_with_no_defaults = len(args) - len(defaults)

    if arg_index < args_with_no_defaults:
        return DefaultArgSpec(False, None)
    else:
        value = defaults[arg_index - args_with_no_defaults]
        if (type(value) is str):
            value = '"%s"' % value
        return DefaultArgSpec(True, value)

def get_method_sig(method):
    """ Given a function, it returns a string that pretty much looks how the
    function signature would be written in python.

    :param method: a python method
    :return: A string similar describing the pythong method signature.
    eg: "my_method(first_argArg, second_arg=42, third_arg='something')"
    """

    # The return value of ArgSpec is a bit weird, as the list of arguments and
    # list of defaults are returned in separate array.
    # eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],
    # varargs=None, keywords=None, defaults=(42, 'something'))
    argspec = inspect.getargspec(method)
    arg_index=0
    args = []

    # Use the args and defaults array returned by argspec and find out
    # which arguments has default
    for arg in argspec.args:
        default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)
        if default_arg.has_default:
            args.append("%s=%s" % (arg, default_arg.default_value))
        else:
            args.append(arg)
        arg_index += 1
    return "%s(%s)" % (method.__name__, ", ".join(args))


if __name__ == '__main__':
    def my_method(first_arg, second_arg=42, third_arg='something'):
        pass

    print get_method_sig(my_method)
    # my_method(first_argArg, second_arg=42, third_arg="something")

回答 3

尝试调用help一个对象以了解它。

>>> foo = [1, 2, 3]
>>> help(foo.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end

Try calling help on an object to find out about it.

>>> foo = [1, 2, 3]
>>> help(foo.append)
Help on built-in function append:

append(...)
    L.append(object) -- append object to end

回答 4

可能要晚一些,但是如果您还想保留参数的顺序及其默认值,则可以使用抽象语法树模块(ast)

这是一个概念证明(请注意,对参数进行排序并将其与默认值匹配的代码肯定可以得到改善/更加清晰):

import ast

for class_ in [c for c in module.body if isinstance(c, ast.ClassDef)]:
    for method in [m for m in class_.body if isinstance(m, ast.FunctionDef)]:
        args = []
        if method.args.args:
            [args.append([a.col_offset, a.id]) for a in method.args.args]
        if method.args.defaults:
            [args.append([a.col_offset, '=' + a.id]) for a in method.args.defaults]
        sorted_args = sorted(args)
        for i, p in enumerate(sorted_args):
            if p[1].startswith('='):
                sorted_args[i-1][1] += p[1]
        sorted_args = [k[1] for k in sorted_args if not k[1].startswith('=')]

        if method.args.vararg:
            sorted_args.append('*' + method.args.vararg)
        if method.args.kwarg:
            sorted_args.append('**' + method.args.kwarg)

        signature = '(' + ', '.join(sorted_args) + ')'

        print method.name + signature

Maybe a bit late to the party, but if you also want to keep the order of the arguments and their defaults, then you can use the Abstract Syntax Tree module (ast).

Here’s a proof of concept (beware the code to sort the arguments and match them to their defaults can definitely be improved/made more clear):

import ast

for class_ in [c for c in module.body if isinstance(c, ast.ClassDef)]:
    for method in [m for m in class_.body if isinstance(m, ast.FunctionDef)]:
        args = []
        if method.args.args:
            [args.append([a.col_offset, a.id]) for a in method.args.args]
        if method.args.defaults:
            [args.append([a.col_offset, '=' + a.id]) for a in method.args.defaults]
        sorted_args = sorted(args)
        for i, p in enumerate(sorted_args):
            if p[1].startswith('='):
                sorted_args[i-1][1] += p[1]
        sorted_args = [k[1] for k in sorted_args if not k[1].startswith('=')]

        if method.args.vararg:
            sorted_args.append('*' + method.args.vararg)
        if method.args.kwarg:
            sorted_args.append('**' + method.args.kwarg)

        signature = '(' + ', '.join(sorted_args) + ')'

        print method.name + signature

回答 5

如果您只想打印功能,请使用pydoc。

import pydoc    

def foo(arg1, arg2, *args, **kwargs):                                                                    
    '''Some foo fn'''                                                                                    
    pass                                                                                                 

>>> print pydoc.render_doc(foo).splitlines()[2]
foo(arg1, arg2, *args, **kwargs)

如果您尝试实际分析功能签名,请使用检查模块的argspec。在将用户的挂钩脚本功能验证到通用框架中时,我必须这样做。

If all you’re trying to do is print the function then use pydoc.

import pydoc    

def foo(arg1, arg2, *args, **kwargs):                                                                    
    '''Some foo fn'''                                                                                    
    pass                                                                                                 

>>> print pydoc.render_doc(foo).splitlines()[2]
foo(arg1, arg2, *args, **kwargs)

If you’re trying to actually analyze the function signature then use argspec of the inspection module. I had to do that when validating a user’s hook script function into a general framework.


回答 6

示例代码:

import inspect
from collections import OrderedDict


def get_signature(fn):
    params = inspect.signature(fn).parameters
    args = []
    kwargs = OrderedDict()
    for p in params.values():
        if p.default is p.empty:
            args.append(p.name)
        else:
            kwargs[p.name] = p.default
    return args, kwargs


def test_sig():
    def fn(a, b, c, d=3, e="abc"):
        pass

    assert get_signature(fn) == (
        ["a", "b", "c"], OrderedDict([("d", 3), ("e", "abc")])
    )

Example code:

import inspect
from collections import OrderedDict


def get_signature(fn):
    params = inspect.signature(fn).parameters
    args = []
    kwargs = OrderedDict()
    for p in params.values():
        if p.default is p.empty:
            args.append(p.name)
        else:
            kwargs[p.name] = p.default
    return args, kwargs


def test_sig():
    def fn(a, b, c, d=3, e="abc"):
        pass

    assert get_signature(fn) == (
        ["a", "b", "c"], OrderedDict([("d", 3), ("e", "abc")])
    )

回答 7

在命令行(IPython)中使用%pdef,它将仅打印签名。

例如 %pdef np.loadtxt

 np.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes')

Use %pdef in the command line (IPython), it will print only the signature.

e.g. %pdef np.loadtxt

 np.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes')

Python函数作为函数参数吗?

问题:Python函数作为函数参数吗?

Python函数可以作为另一个函数的参数吗?

说:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass

所以这基本上是两个问题:

  1. 可以吗?
  2. 如果是的话,如何在其他函数中使用该函数?我需要使用exec(),eval()还是类似的东西?从来不需要与他们搞混。

顺便说一句,extraArgs是anotherfunc参数的列表/元组。

Can a Python function be an argument of another function?

Say:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass

So this is basically two questions:

  1. Is it allowed at all?
  2. And if it is, how do I use the function inside the other function? Would I need to use exec(), eval() or something like that? Never needed to mess with them.

BTW, extraArgs is a list/tuple of anotherfunc’s arguments.


回答 0

Python函数可以作为另一个函数的参数吗?

是。

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

更具体地说…带有各种参数…

>>> def x(a,b):
...     print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>

Can a Python function be an argument of another function?

Yes.

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

To be more specific … with various arguments …

>>> def x(a,b):
...     print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>

回答 1

这是使用*args(以及可选)的另一种方法**kwargs

def a(x, y):
  print x, y

def b(other, function, *args, **kwargs):
  function(*args, **kwargs)
  print other

b('world', a, 'hello', 'dude')

输出量

hello dude
world

需要注意的是function*args**kwargs必须按照这个顺序和必须的函数调用该函数的最后的参数。

Here’s another way using *args (and also optionally), **kwargs:

def a(x, y):
  print x, y

def b(other, function, *args, **kwargs):
  function(*args, **kwargs)
  print other

b('world', a, 'hello', 'dude')

Output

hello dude
world

Note that function, *args, **kwargs have to be in that order and have to be the last arguments to the function calling the function.


回答 2

Python中的函数是一流的对象。但是您的函数定义有点偏离

def myfunc(anotherfunc, extraArgs, extraKwArgs):
  return anotherfunc(*extraArgs, **extraKwArgs)

Functions in Python are first-class objects. But your function definition is a bit off.

def myfunc(anotherfunc, extraArgs, extraKwArgs):
  return anotherfunc(*extraArgs, **extraKwArgs)

回答 3

当然,这就是python在第一个参数为函数的情况下实现以下方法的原因:

  • map(function,iterable,…)-将函数应用于iterable的每个项目并返回结果列表。
  • filter(function,iterable)-从这些iterable的元素构造一个列表,对于这些元素,函数将返回true。
  • reduce(function,iterable [,initializer])-将两个参数的函数从左到右累计应用于iterable的项,以将iterable减少为单个值。
  • Lambdas

Sure, that is why python implements the following methods where the first parameter is a function:

  • map(function, iterable, …) – Apply function to every item of iterable and return a list of the results.
  • filter(function, iterable) – Construct a list from those elements of iterable for which function returns true.
  • reduce(function, iterable[,initializer]) – Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
  • lambdas

回答 4

  1. 是的,允许。
  2. 您可以像使用其他函数一样使用该函数: anotherfunc(*extraArgs)
  1. Yes, it’s allowed.
  2. You use the function as you would any other: anotherfunc(*extraArgs)

回答 5

  1. 是。通过在输入参数中包含函数调用,可以一次调用两个(或多个)函数。

例如:

def anotherfunc(inputarg1, inputarg2):
    pass
def myfunc(func = anotherfunc):
    print func

调用myfunc时,请执行以下操作:

myfunc(anotherfunc(inputarg1, inputarg2))

这将打印anotherfunc的返回值。

希望这可以帮助!

  1. Yes. By including the function call in your input argument/s, you can call two (or more) functions at once.

For example:

def anotherfunc(inputarg1, inputarg2):
    pass
def myfunc(func = anotherfunc):
    print func

When you call myfunc, you do this:

myfunc(anotherfunc(inputarg1, inputarg2))

This will print the return value of anotherfunc.

Hope this helps!


回答 6

函数内部的函数:我们也可以将函数用作参数。

换句话说,我们可以说函数的输出也是对象的引用,请参阅下文,内部函数的输出如何引用外部函数,如下所示。

def out_func(a):

  def in_func(b):
       print(a + b + b + 3)
  return in_func

obj = out_func(1)
print(obj(5))

结果将是.. 14

希望这可以帮助。

Function inside function: we can use the function as parameter too..

In other words, we can say an output of a function is also a reference for an object, see below how the output of inner function is referencing to the outside function like below..

def out_func(a):

  def in_func(b):
       print(a + b + b + 3)
  return in_func

obj = out_func(1)
print(obj(5))

the result will be.. 14

Hope this helps.


回答 7

def x(a):
    print(a)
    return a

def y(a):
    return a

y(x(1))
def x(a):
    print(a)
    return a

def y(a):
    return a

y(x(1))

回答 8

def x(a):
    print(a)
    return a

def y(func_to_run, a):
    return func_to_run(a)

y(x, 1)

我认为这将是一个更适当的示例。现在我想知道的是,是否有一种方法可以编码要在提交给另一个函数的参数中使用的函数。我相信在C ++中,但是在Python中我不确定。

def x(a):
    print(a)
    return a

def y(func_to_run, a):
    return func_to_run(a)

y(x, 1)

That I think would be a more proper sample. Now what I wonder is if there is a way to code the function to use within the argument submission to another function. I believe there is in C++, but in Python I am not sure.


回答 9

装饰器在Python中非常强大,因为它允许程序员将函数作为参数传递,也可以在另一个函数中定义函数。

def decorator(func):
      def insideFunction():
        print("This is inside function before execution")
        func()
      return insideFunction

def func():
    print("I am argument function")

func_obj = decorator(func) 
func_obj()

输出量

  • 这是执行之前的内部函数
  • 我是参数函数

Decorators are very powerful in Python since it allows programmers to pass function as argument and can also define function inside another function.

def decorator(func):
      def insideFunction():
        print("This is inside function before execution")
        func()
      return insideFunction

def func():
    print("I am argument function")

func_obj = decorator(func) 
func_obj()

Output

  • This is inside function before execution
  • I am argument function

您可以列出函数接收的关键字参数吗?

问题:您可以列出函数接收的关键字参数吗?

我有一个字典,我需要将键/值作为关键字参数传递..例如。

d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)

这可以正常工作,但是如果d_args字典中有一些example函数不接受的值,则它显然会死掉。.说,如果将示例函数定义为def example(kw2):

这是一个问题,因为我无法控制d_argsexample函数的生成。它们都来自外部模块,并且example仅接受dict中的某些关键字参数。

理想情况下,我会做

parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)

我可能只是从有效的关键字参数列表中过滤出dict,但是我想知道:是否有一种方法可以以编程方式列出特定函数所采用的关键字参数?

I have a dict, which I need to pass key/values as keyword arguments.. For example..

d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)

This works fine, but if there are values in the d_args dict that are not accepted by the example function, it obviously dies.. Say, if the example function is defined as def example(kw2):

This is a problem since I don’t control either the generation of the d_args, or the example function.. They both come from external modules, and example only accepts some of the keyword-arguments from the dict..

Ideally I would just do

parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)

I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: Is there a way to programatically list the keyword arguments the a specific function takes?


回答 0

比起直接检查代码对象并计算出变量,更好的方法是使用检查模块。

>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

如果您想知道它是否可以与一组特定的args一起调用,则需要未指定默认值的args。这些可以通过以下方式获得:

def getRequiredArgs(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

然后一个函数来告诉您特定字典缺少什么:

def missingArgs(func, argdict):
    return set(getRequiredArgs(func)).difference(argdict)

同样,要检查无效的参数,请使用:

def invalidArgs(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

因此,是否可以调用的完整测试是:

def isCallableWithArgs(func, argdict):
    return not missingArgs(func, argdict) and not invalidArgs(func, argdict)

(这仅在python的arg解析方面是好的。任何运行时检查kwargs中的无效值显然都无法检测到。)

A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.

>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))

If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:

def getRequiredArgs(func):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if defaults:
        args = args[:-len(defaults)]
    return args   # *args and **kwargs are not required, so ignore them.

Then a function to tell what you are missing from your particular dict is:

def missingArgs(func, argdict):
    return set(getRequiredArgs(func)).difference(argdict)

Similarly, to check for invalid args, use:

def invalidArgs(func, argdict):
    args, varargs, varkw, defaults = inspect.getargspec(func)
    if varkw: return set()  # All accepted
    return set(argdict) - set(args)

And so a full test if it is callable is :

def isCallableWithArgs(func, argdict):
    return not missingArgs(func, argdict) and not invalidArgs(func, argdict)

(This is good only as far as python’s arg parsing. Any runtime checks for invalid values in kwargs obviously can’t be detected.)


回答 1

这将打印所有可传递参数,关键字和非关键字参数的名称:

def func(one, two="value"):
    y = one, two
    return y
print func.func_code.co_varnames[:func.func_code.co_argcount]

这是因为第一个co_varnames始终是参数(下一个是局部变量,y如上例所示)。

所以现在您可以拥有一个功能:

def getValidArgs(func, argsDict):
    '''Return dictionary without invalid function arguments.'''
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validArgs)

然后可以这样使用:

>>> func(**getValidArgs(func, args))

编辑:一个小的补充:如果您真的只需要一个函数的关键字参数,则可以使用func_defaults属性来提取它们:

def getValidKwargs(func, argsDict):
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    kwargsLen = len(func.func_defaults) # number of keyword arguments
    validKwargs = validArgs[-kwargsLen:] # because kwargs are last
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validKwargs)

现在,您可以使用已知的args调用函数,但是要提取kwargs,例如:

func(param1, param2, **getValidKwargs(func, kwargsDict))

假定签名中func不使用no *args**kwargsmagic。

This will print names of all passable arguments, keyword and non-keyword ones:

def func(one, two="value"):
    y = one, two
    return y
print func.func_code.co_varnames[:func.func_code.co_argcount]

This is because first co_varnames are always parameters (next are local variables, like y in the example above).

So now you could have a function:

def getValidArgs(func, argsDict):
    '''Return dictionary without invalid function arguments.'''
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validArgs)

Which you then could use like this:

>>> func(**getValidArgs(func, args))

EDIT: A small addition: if you really need only keyword arguments of a function, you can use the func_defaults attribute to extract them:

def getValidKwargs(func, argsDict):
    validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]
    kwargsLen = len(func.func_defaults) # number of keyword arguments
    validKwargs = validArgs[-kwargsLen:] # because kwargs are last
    return dict((key, value) for key, value in argsDict.iteritems() 
                if key in validKwargs)

You could now call your function with known args, but extracted kwargs, e.g.:

func(param1, param2, **getValidKwargs(func, kwargsDict))

This assumes that func uses no *args or **kwargs magic in its signature.


回答 2

在Python 3.0中:

>>> import inspect
>>> import fileinput
>>> print(inspect.getfullargspec(fileinput.input))
FullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],
varargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], 
kwdefaults=None, annotations={})

In Python 3.0:

>>> import inspect
>>> import fileinput
>>> print(inspect.getfullargspec(fileinput.input))
FullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],
varargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], 
kwdefaults=None, annotations={})

回答 3

对于Python 3解决方案,您可以inspect.signature根据想要了解的参数种类使用和过滤。

以带有位置或关键字,仅关键字,var positional和var关键字参数的样本函数为例:

def spam(a, b=1, *args, c=2, **kwargs):
    print(a, b, args, c, kwargs)

您可以为其创建签名对象:

from inspect import signature
sig =  signature(spam)

然后使用列表推导进行过滤以找出所需的详细信息:

>>> # positional or keyword
>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]
['a', 'b']
>>> # keyword only
>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]
['c']

同样,对于使用p.VAR_POSITIONALvar关键字和var关键字与的变量VAR_KEYWORD

另外,您可以在if中添加一个子句,以通过检查是否p.default等于来检查是否存在默认值p.empty

For a Python 3 solution, you can use inspect.signature and filter according to the kind of parameters you’d like to know about.

Taking a sample function with positional or keyword, keyword-only, var positional and var keyword parameters:

def spam(a, b=1, *args, c=2, **kwargs):
    print(a, b, args, c, kwargs)

You can create a signature object for it:

from inspect import signature
sig =  signature(spam)

and then filter with a list comprehension to find out the details you need:

>>> # positional or keyword
>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]
['a', 'b']
>>> # keyword only
>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]
['c']

and, similarly, for var positionals using p.VAR_POSITIONAL and var keyword with VAR_KEYWORD.

In addition, you can add a clause to the if to check if a default value exists by checking if p.default equals p.empty.


回答 4

扩展DzinX的答案:

argnames = example.func_code.co_varnames[:func.func_code.co_argcount]
args = dict((key, val) for key,val in d_args.iteritems() if key in argnames)
example(**args)

Extending DzinX’s answer:

argnames = example.func_code.co_varnames[:func.func_code.co_argcount]
args = dict((key, val) for key,val in d_args.iteritems() if key in argnames)
example(**args)

如何使用可选参数创建Python函数?

问题:如何使用可选参数创建Python函数?

我有一个带几个参数的Python函数。在某些情况下,可以忽略其中一些参数。

def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None):
    #code

这些参数d通过h是字符串,每个都有不同的含义。我可以选择要以任何组合形式传递的可选参数,这一点很重要。例如,(a, b, C, d, e)(a, b, C, g, h),,或(a, b, C, d, e, f,或所有它们(这些是我的选择)。

如果我可以重载该函数,那就太好了-但我读到Python不支持重载。我试图在列表中插入一些必需的int参数-并收到参数不匹配错误。

现在,我正在发送空字符串来代替前几个缺少的参数作为占位符。我希望能够仅使用实际值来调用函数。

有什么办法吗?我可以传递一个列表而不是参数列表吗?

现在,使用ctypes的原型看起来像:

_fdll.some_function.argtypes = [c_void_p, c_char_p, c_int, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p]

I have a Python function which takes several arguments. Some of these arguments could be omitted in some scenarios.

def some_function (self, a, b, c, d = None, e = None, f = None, g = None, h = None):
    #code

The arguments d through h are strings which each have different meanings. It is important that I can choose which optional parameters to pass in any combination. For example, (a, b, C, d, e), or (a, b, C, g, h), or (a, b, C, d, e, f, or all of them (these are my choices).

It would be great if I could overload the function – but I read that Python does not support overloading. I tried to insert some of the required int arguments in the list – and got an argument mismatch error.

Right now I am sending empty strings in place of the first few missing arguments as placeholders. I would like to be able to call a function just using actual values.

Is there any way to do this? Could I pass a list instead of the argument list?

Right now the prototype using ctypes looks something like:

_fdll.some_function.argtypes = [c_void_p, c_char_p, c_int, c_char_p, c_char_p, c_char_p, c_char_p, c_char_p]

回答 0

尝试像这样调用它:obj.some_function( '1', 2, '3', g="foo", h="bar" )。在所需的位置参数之后,可以按名称指定特定的可选参数。

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.


回答 1

只需使用*args参数,它可以让您在后面传递任意数量的参数a,b,c。您将不得不在映射中添加一些逻辑args-> c,d,e,f但它是过载的“方式”。

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

它会打印出 c,d,e,f


同样,您可以使用kwargs参数,然后可以命名参数。

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

然后kwargs将有一个字典,其中包含所有在之后被键值的参数a,b

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a “way” of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b


TypeError:method()接受1个位置参数,但给出了2个

问题:TypeError:method()接受1个位置参数,但给出了2个

如果我有课…

class MyClass:

    def method(arg):
        print(arg)

…我用来创建对象的…

my_object = MyClass()

我这样称呼method("foo")

>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

…为什么当我只给出一个参数时,Python告诉我给它两个参数?

If I have a class…

class MyClass:

    def method(arg):
        print(arg)

…which I use to create an object…

my_object = MyClass()

…on which I call method("foo") like so…

>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

…why does Python tell me I gave it two arguments, when I only gave one?


回答 0

在Python中,这是:

my_object.method("foo")

…是语法糖,口译员在后台将其翻译为:

MyClass.method(my_object, "foo")

您可以看到,它确实有两个参数-从调用者的角度来看,只是第一个参数是隐式的。

这是因为大多数方法会对被调用的对象进行某些处理,因此需要某种方法在该方法内部引用该对象。按照惯例,第一个参数self在方法定义内调用:

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

如果您呼叫method("foo")的实例MyNewClass,它会按预期运作:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

有时(但不经常),您实际上不在乎您的方法所绑定的对象,在这种情况下,您可以使用内置函数来修饰该方法,staticmethod()例如:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

…在这种情况下,您无需self在方法定义中添加参数,它仍然有效:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

In Python, this:

my_object.method("foo")

…is syntactic sugar, which the interpreter translates behind the scenes into:

MyClass.method(my_object, "foo")

…which, as you can see, does indeed have two arguments – it’s just that the first one is implicit, from the point of view of the caller.

This is because most methods do some work with the object they’re called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition:

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

If you call method("foo") on an instance of MyNewClass, it works as expected:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

Occasionally (but not often), you really don’t care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod() function to say so:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

…in which case you don’t need to add a self argument to the method definition, and it still works:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

回答 1

遇到此类错误时要考虑的其他事项:

我遇到了这个错误消息,发现这篇文章很有帮助。事实证明,我重写了__init__()存在对象继承的位置。

继承的示例相当长,因此我将跳到一个不使用继承的更简单的示例:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

结果是:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm没有抓住这种错别字。Notepad ++也没有(其他编辑器/ IDE也可能)。

当然,这是一个“不带任何参数”的TypeError,与期望得到一个的“得到两个”没有太大区别,就Python中的对象初始化而言。

解决主题:在语法上正确的情况下将使用重载初始化程序,但在语法上正确的情况下将被使用,而是使用内置初始化程序。该对象不会期望/处理此问题,并且会引发错误。

如果出现sytax错误:修复很简单,只需编辑自定义init语句即可:

def __init__(self, name):
    self.name = name

Something else to consider when this type of error is encountered:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__() where there was object inheritance.

The inherited example is rather long, so I’ll skip to a more simple example that doesn’t use inheritance:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn’t catch this typo. Nor did Notepad++ (other editors/IDE’s might).

Granted, this is a “takes no parameters” TypeError, it isn’t much different than “got two” when expecting one, in terms of object initialization in Python.

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won’t expect/handle this and the error is thrown.

In the case of the sytax error: The fix is simple, just edit the custom init statement:

def __init__(self, name):
    self.name = name

回答 2

简单来说。

在Python中,您应该将self参数作为第一个参数添加到类中所有已定义的方法中:

class MyClass:
  def method(self, arg):
    print(arg)

然后,您可以根据自己的直觉使用您的方法:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

这应该可以解决您的问题:)

为了更好地理解,您还可以阅读以下问题的答案:自我的目的是什么?

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?


回答 3

Python的新手**,以错误的方式使用Python的功能时遇到了这个问题。尝试从某处调用此定义:

def create_properties_frame(self, parent, **kwargs):

使用没有双星的通话会导致问题:

self.create_properties_frame(frame, kw_gsp)

TypeError:create_properties_frame()接受2个位置参数,但给出了3个

解决方案是**在参数中添加:

self.create_properties_frame(frame, **kw_gsp)

Newcomer to Python, I had this issue when I was using the Python’s ** feature in a wrong way. Trying to call this definition from somewhere:

def create_properties_frame(self, parent, **kwargs):

using a call without a double star was causing the problem:

self.create_properties_frame(frame, kw_gsp)

TypeError: create_properties_frame() takes 2 positional arguments but 3 were given

The solution is to add ** to the argument:

self.create_properties_frame(frame, **kw_gsp)

回答 4

当您未指定参数No __init__()或任何其他寻找方法时,就会发生这种情况。

例如:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

当您运行上述程序时,它给您这样的错误:

TypeError:__init __()接受1个位置参数,但给出了6个

我们如何摆脱这件事?

只需传递参数,__init__()寻找什么方法

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

It occurs when you don’t specify the no of parameters the __init__() or any other method looking for.

For example:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj=Dog("JIMMY",1,2,3,"WOOF")

When you run the above programme, it gives you an error like that:

TypeError: __init__() takes 1 positional argument but 6 were given

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

回答 5

您实际上应该创建一个类:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
    return self.acc

You should actually create a class:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
    return self.acc

回答 6

就我而言,我忘记添加 ()

我正在这样调用方法

obj = className.myMethod

但是应该是这样

obj = className.myMethod()

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

回答 7

cls参数传递到@classmethod以解决此问题。

@classmethod
def test(cls):
    return ''

Pass cls parameter into @classmethod to resolve this problem.

@classmethod
def test(cls):
    return ''

在Python中打印多个参数

问题:在Python中打印多个参数

这只是我的代码的一部分:

print("Total score for %s is %s  ", name, score)

但我希望它打印出来:

“(姓名)的总分是(分数)”

其中name是列表中的变量,score是整数。如果有帮助的话,这就是Python 3.3。

This is just a snippet of my code:

print("Total score for %s is %s  ", name, score)

But I want it to print out:

“Total score for (name) is (score)”

where name is a variable in a list and score is an integer. This is Python 3.3 if that helps at all.


回答 0

有很多方法可以做到这一点。要使用%-formatting 修复当前代码,您需要传入一个元组:

  1. 将其作为元组传递:

    print("Total score for %s is %s" % (name, score))

具有单个元素的元组看起来像('this',)

这是其他一些常见的实现方法:

  1. 将其作为字典传递:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})

还有一种新型的字符串格式,可能更容易阅读:

  1. 使用新型的字符串格式:

    print("Total score for {} is {}".format(name, score))
  2. 使用带有数字的新型字符串格式(可用于重新排序或多次打印相同的字符):

    print("Total score for {0} is {1}".format(name, score))
  3. 使用具有显式名称的新型字符串格式:

    print("Total score for {n} is {s}".format(n=name, s=score))
  4. 连接字符串:

    print("Total score for " + str(name) + " is " + str(score))

我认为最清楚的两个是:

  1. 只需将值作为参数传递:

    print("Total score for", name, "is", score)

    如果您不希望print在上面的示例中自动插入空格,请更改sep参数:

    print("Total score for ", name, " is ", score, sep='')

    如果您使用的是Python 2,将不能使用最后两个,因为print这不是Python 2中的函数。不过,您可以从__future__以下方式导入此行为:

    from __future__ import print_function
  2. f在Python 3.6中使用新的-string格式:

    print(f'Total score for {name} is {score}')

There are many ways to do this. To fix your current code using %-formatting, you need to pass in a tuple:

  1. Pass it as a tuple:

    print("Total score for %s is %s" % (name, score))
    

A tuple with a single element looks like ('this',).

Here are some other common ways of doing it:

  1. Pass it as a dictionary:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

There’s also new-style string formatting, which might be a little easier to read:

  1. Use new-style string formatting:

    print("Total score for {} is {}".format(name, score))
    
  2. Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):

    print("Total score for {0} is {1}".format(name, score))
    
  3. Use new-style string formatting with explicit names:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. Concatenate strings:

    print("Total score for " + str(name) + " is " + str(score))
    

The clearest two, in my opinion:

  1. Just pass the values as parameters:

    print("Total score for", name, "is", score)
    

    If you don’t want spaces to be inserted automatically by print in the above example, change the sep parameter:

    print("Total score for ", name, " is ", score, sep='')
    

    If you’re using Python 2, won’t be able to use the last two because print isn’t a function in Python 2. You can, however, import this behavior from __future__:

    from __future__ import print_function
    
  2. Use the new f-string formatting in Python 3.6:

    print(f'Total score for {name} is {score}')
    

回答 1

有很多打印方法。

让我们看另一个例子。

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

There are many ways to print that.

Let’s have a look with another example.

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

回答 2

使用方法.format()

print("Total score for {0} is {1}".format(name, score))

要么:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

要么:

print("Total score for" + name + " is " + score)

要么:

`print("Total score for %s is %d" % (name, score))`

Use: .format():

print("Total score for {0} is {1}".format(name, score))

Or:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

Or:

print("Total score for" + name + " is " + score)

Or:

`print("Total score for %s is %d" % (name, score))`

回答 3

在Python 3.6中,f-string它更加干净。

在早期版本中:

print("Total score for %s is %s. " % (name, score))

在Python 3.6中:

print(f'Total score for {name} is {score}.')

会做。

它更高效,更优雅。

In Python 3.6, f-string is much cleaner.

In earlier version:

print("Total score for %s is %s. " % (name, score))

In Python 3.6:

print(f'Total score for {name} is {score}.')

will do.

It is more efficient and elegant.


回答 4

保持简单,我个人喜欢字符串连接:

print("Total score for " + name + " is " + score)

它同时适用于Python 2.7和3.X。

注意:如果score是一个int,则应将其转换为str

print("Total score for " + name + " is " + str(score))

Keeping it simple, I personally like string concatenation:

print("Total score for " + name + " is " + score)

It works with both Python 2.7 an 3.X.

NOTE: If score is an int, then, you should convert it to str:

print("Total score for " + name + " is " + str(score))

回答 5

你试一试:

print("Total score for", name, "is", score)

Just try:

print("Total score for", name, "is", score)

回答 6

只要遵循这个

idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))

要么

idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))

忘记所有其他格式,否则大脑将无法映射所有格式。

Just follow this

idiot_type = "the biggest idiot"
year = 22
print("I have been {} for {} years ".format(idiot_type, years))

OR

idiot_type = "the biggest idiot"
year = 22
print("I have been %s for %s years."% (idiot_type, year))

And forget all others, else the brain won’t be able to map all the formats.


回答 7

print("Total score for %s is %s  " % (name, score))

%s可以替换为%d%f

print("Total score for %s is %s  " % (name, score))

%s can be replace by %d or %f


回答 8

用途f-string

print(f'Total score for {name} is {score}')

要么

用途.format

print("Total score for {} is {}".format(name, score))

Use f-string:

print(f'Total score for {name} is {score}')

Or

Use .format:

print("Total score for {} is {}".format(name, score))

回答 9

如果score是数字,则

print("Total score for %s is %d" % (name, score))

如果score是一个字符串,则

print("Total score for %s is %s" % (name, score))

如果score是数字,%d则为,如果是字符串%s,则为,如果score是浮点型,则为%f

If score is a number, then

print("Total score for %s is %d" % (name, score))

If score is a string, then

print("Total score for %s is %s" % (name, score))

If score is a number, then it’s %d, if it’s a string, then it’s %s, if score is a float, then it’s %f


回答 10

这是我的工作:

print("Total score for " + name + " is " + score)

请记住在for前后放置一个空格is

This is what I do:

print("Total score for " + name + " is " + score)

Remember to put a space after for and before and after is.


普通参数与关键字参数

问题:普通参数与关键字参数

“关键字参数”与常规参数有何不同?不能将所有参数都传递为name=value而不是使用位置语法吗?

How are “keyword arguments” different from regular arguments? Can’t all arguments be passed as name=value instead of using positional syntax?


回答 0

有两个相关的概念,都称为“ 关键字参数 ”。

在调用方(这是其他评论者提到的),您可以通过名称指定一些函数自变量。您必须在所有不带名称的参数(位置参数)之后提及它们,并且对于所有根本没有提及的参数,都必须有默认值

另一个概念是在函数定义方面:您可以定义一个按名称接受参数的函数-甚至不必指定这些名称是什么。这些是纯关键字参数,不能按位置传递。语法是

def my_function(arg1, arg2, **kwargs)

您传递给此函数的所有关键字参数都将放入名为的字典中kwargs。您可以在运行时检查此字典的键,如下所示:

def my_function(**kwargs):
    print str(kwargs)

my_function(a=12, b="abc")

{'a': 12, 'b': 'abc'}

There are two related concepts, both called “keyword arguments“.

On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.

The other concept is on the function definition side: you can define a function that takes parameters by name — and you don’t even have to specify what those names are. These are pure keyword arguments, and can’t be passed positionally. The syntax is

def my_function(arg1, arg2, **kwargs)

Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:

def my_function(**kwargs):
    print str(kwargs)

my_function(a=12, b="abc")

{'a': 12, 'b': 'abc'}

回答 1

最后一种语言功能在区分上很重要。考虑以下功能:

def foo(*positional, **keywords):
    print "Positional:", positional
    print "Keywords:", keywords

*positional参数将存储传递给的所有位置参数foo(),对您可以提供的数量没有限制。

>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}

**keywords参数将存储任何关键字参数:

>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}

当然,您可以同时使用两者:

>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}

这些功能很少使用,但有时它们非常有用,并且重要的是要知道哪些参数是位置参数或关键字。

There is one last language feature where the distinction is important. Consider the following function:

def foo(*positional, **keywords):
    print "Positional:", positional
    print "Keywords:", keywords

The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.

>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}

The **keywords argument will store any keyword arguments:

>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}

And of course, you can use both at the same time:

>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}

These features are rarely used, but occasionally they are very useful, and it’s important to know which arguments are positional or keywords.


回答 2

使用关键字参数与普通参数一样,只是顺序无关紧要。例如,下面的两个函数调用是相同的:

def foo(bar, baz):
    pass

foo(1, 2)
foo(baz=2, bar=1)

Using keyword arguments is the same thing as normal arguments except order doesn’t matter. For example the two functions calls below are the same:

def foo(bar, baz):
    pass

foo(1, 2)
foo(baz=2, bar=1)

回答 3

位置参数

他们前面没有关键字。顺序很重要!

func(1,2,3, "foo")

关键字参数

他们在前面有关键字。它们可以是任何顺序!

func(foo="bar", baz=5, hello=123)

func(baz=5, foo="bar", hello=123)

您还应该知道,如果您使用默认参数并且忽略插入关键字,那么顺序将很重要!

def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)

Positional Arguments

They have no keywords before them. The order is important!

func(1,2,3, "foo")

Keyword Arguments

They have keywords in the front. They can be in any order!

func(foo="bar", baz=5, hello=123)

func(baz=5, foo="bar", hello=123)

You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!

def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)

回答 4

有两种方法可以将参数值分配给函数参数。

  1. 按位置。位置参数没有关键字,而是首先分配的。

  2. 按关键字。关键字参数具有关键字,并且在位置参数之后排在第二位。

请注意,可以选择使用位置参数。

如果不使用位置参数,那么-是的- 编写的所有内容实际上都是关键字参数。

调用一个函数您对使用位置或关键字或混合物的决定。您可以根据需要选择所有关键字。我们中有些人没有做出选择,而是使用位置参数。

There are two ways to assign argument values to function parameters, both are used.

  1. By Position. Positional arguments do not have keywords and are assigned first.

  2. By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.

Note that you have the option to use positional arguments.

If you don’t use positional arguments, then — yes — everything you wrote turns out to be a keyword argument.

When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.


回答 5

令我感到惊讶的是,似乎没有人指出可以像这样通过字典来传递形式参数的键参数参数。

>>> def func(a='a', b='b', c='c', **kwargs):
...    print 'a:%s, b:%s, c:%s' % (a, b, c)
... 
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>> 

I’m surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.

>>> def func(a='a', b='b', c='c', **kwargs):
...    print 'a:%s, b:%s, c:%s' % (a, b, c)
... 
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>> 

回答 6

使用Python 3里,你可以有两个必需和非必需的关键字参数


可选:(为参数“ b”定义的默认值)

def func1(a, *, b=42):
    ...
func1(value_for_a) # b is optional and will default to 42

必需(未为参数“ b”定义默认值):

def func2(a, *, b):
    ... 
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`

如果彼此之间有许多相似的参数,尤其是当它们属于同一类型时,这会有所帮助,在这种情况下,我更喜欢使用命名参数,或者如果参数属于同一类,则我会创建一个自定义类。

Using Python 3 you can have both required and non-required keyword arguments:


Optional: (default value defined for param ‘b’)

def func1(a, *, b=42):
    ...
func1(value_for_a) # b is optional and will default to 42

Required (no default value defined for param ‘b’):

def func2(a, *, b):
    ... 
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`

This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.


回答 7

令我惊讶的是,没有人提到您可以使用*argsand **kwargs从此站点)混合使用位置参数和关键字参数来进行类似的事情:

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

这使您可以使用任意关键字参数,这些参数可能包含您不想预先定义的键。

I’m surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

This allows you to use arbitrary keyword arguments that may have keys you don’t want to define upfront.


回答 8

我正在寻找一个使用类型注释的默认kwargs的示例:

def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
     return ' '.join([a, b, c, str(kwargs)])

例:

>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}

I was looking for an example that had default kwargs using type annotation:

def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
     return ' '.join([a, b, c, str(kwargs)])

example:

>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}

回答 9

只是补充/添加一种方法来定义调用函数时未在关键字中分配的参数默认值

def func(**keywargs):
if 'my_word' not in keywargs:
    word = 'default_msg'
else:
    word = keywargs['my_word']
return word

通过以下方式调用:

print(func())
print(func(my_word='love'))

你会得到:

default_msg
love

阅读更多关于*args**kwargsPython中:https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3

Just suplement/add a way for defining the default value of arguments that is not assigned in key words when calling the function:

def func(**keywargs):
if 'my_word' not in keywargs:
    word = 'default_msg'
else:
    word = keywargs['my_word']
return word

call this by:

print(func())
print(func(my_word='love'))

you’ll get:

default_msg
love

read more about *args and **kwargs in python: https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3


我应该针对Python中的错误/非法参数组合引发哪个异常?

问题:我应该针对Python中的错误/非法参数组合引发哪个异常?

我想知道在Python中指示无效参数组合的最佳做法。我遇到过几种情况,其中您具有如下功能:

def import_to_orm(name, save=False, recurse=False):
    """
    :param name: Name of some external entity to import.
    :param save: Save the ORM object before returning.
    :param recurse: Attempt to import associated objects as well. Because you
        need the original object to have a key to relate to, save must be
        `True` for recurse to be `True`.
    :raise BadValueError: If `recurse and not save`.
    :return: The ORM object.
    """
    pass

唯一令人烦恼的是,每个包装都有自己的包装,通常略有不同BadValueError。我知道在Java中存在java.lang.IllegalArgumentException-是否众所周知每个人都将BadValueError在Python中创建自己的s还是存在另一种首选方法?

I was wondering about the best practices for indicating invalid argument combinations in Python. I’ve come across a few situations where you have a function like so:

def import_to_orm(name, save=False, recurse=False):
    """
    :param name: Name of some external entity to import.
    :param save: Save the ORM object before returning.
    :param recurse: Attempt to import associated objects as well. Because you
        need the original object to have a key to relate to, save must be
        `True` for recurse to be `True`.
    :raise BadValueError: If `recurse and not save`.
    :return: The ORM object.
    """
    pass

The only annoyance with this is that every package has its own, usually slightly differing BadValueError. I know that in Java there exists java.lang.IllegalArgumentException — is it well understood that everybody will be creating their own BadValueErrors in Python or is there another, preferred method?


回答 0

我只会提出ValueError,除非您需要更具体的exceptions。

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

这样做真的没有意义class BadValueError(ValueError):pass-您的自定义类的用法与ValueError相同,那么为什么不使用它呢?

I would just raise ValueError, unless you need a more specific exception..

def import_to_orm(name, save=False, recurse=False):
    if recurse and not save:
        raise ValueError("save must be True if recurse is True")

There’s really no point in doing class BadValueError(ValueError):pass – your custom class is identical in use to ValueError, so why not use that?


回答 1

我会继承 ValueError

class IllegalArgumentError(ValueError):
    pass

有时最好创建自己的异常,但要从内置异常中继承,该异常应尽可能接近您想要的异常。

如果需要捕获该特定错误,请使用一个名称。

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.


回答 2

我认为处理此问题的最佳方法是python本身处理它的方法。Python引发TypeError。例如:

$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0

我们的初级开发人员刚刚在Google搜索“ python异常错误参数”中找到了此页面,而令我惊讶的是,自问这个问题以来,十年来从未出现过明显的(对我而言)答案。

I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example:

$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0

Our junior dev just found this page in a google search for “python exception wrong arguments” and I’m surprised that the obvious (to me) answer wasn’t ever suggested in the decade since this question was asked.


回答 3

我几乎只看到ValueError过这种情况下使用的内建函数。

I’ve mostly just seen the builtin ValueError used in this situation.


回答 4

这取决于参数的问题。

如果参数的类型错误,则引发TypeError。例如,当您获取字符串而不是这些布尔值之一时。

if not isinstance(save, bool):
    raise TypeError(f"Argument save must be of type bool, not {type(save)}")

但是请注意,在Python中我们很少进行此类检查。如果参数确实无效,那么一些更深层的功能可能会为我们带来麻烦。而且,如果我们仅检查布尔值,也许某些代码用户以后会向其提供一个字符串,因为它知道非空字符串始终为True。这可能会救他一个演员。

如果参数包含无效值,请引发ValueError。这似乎更适合您的情况:

if recurse and not save:
    raise ValueError("If recurse is True, save should be True too")

或在此特定情况下,递归的True值表示保存的True值。由于我认为这是从错误中恢复,因此您可能还希望在日志中抱怨。

if recurse and not save:
    logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
    save = True

It depends on what the problem with the arguments is.

If the argument has the wrong type, raise a TypeError. For example, when you get a string instead of one of those Booleans.

if not isinstance(save, bool):
    raise TypeError(f"Argument save must be of type bool, not {type(save)}")

Note, however, that in Python we rarely make any checks like this. If the argument really is invalid, some deeper function will probably do the complaining for us. And if we only check the boolean value, perhaps some code user will later just feed it a string knowing that non-empty strings are always True. It might save him a cast.

If the arguments have invalid values, raise ValueError. This seems more appropriate in your case:

if recurse and not save:
    raise ValueError("If recurse is True, save should be True too")

Or in this specific case, have a True value of recurse imply a True value of save. Since I would consider this a recovery from an error, you might also want to complain in the log.

if recurse and not save:
    logging.warning("Bad arguments in import_to_orm() - if recurse is True, so should save be")
    save = True

回答 5

我不确定我是否同意继承ValueError-我对文档的解释ValueError应由内建函数引发…从中继承或自己引发它似乎不正确。

当内置操作或函数接收到类型正确但值不合适的参数时引发,并且这种情况没有通过诸如IndexError之类的更精确的异常描述。

ValueError异常文档

I’m not sure I agree with inheritance from ValueError — my interpretation of the documentation is that ValueError is only supposed to be raised by builtins… inheriting from it or raising it yourself seems incorrect.

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

ValueError documentation


回答 6

同意Markus关于提出自己的异常的建议,但是该异常的文字应阐明问题出在参数列表中,而不是单个参数值中。我建议:

class BadCallError(ValueError):
    pass

当缺少特定调用所需的关键字参数或参数值分别有效但彼此不一致时使用。 ValueError当特定参数是正确类型但超出范围时,仍将是正确的。

这不是Python中的标准exceptions吗?

总的来说,我希望Python样式在区分函数的错误输入(调用者的错误)和函数内部的错误结果(我的错误)方面更加犀利。因此,可能还存在BadArgumentError来区分参数中的值错误和本地变量中的值错误。

Agree with Markus’ suggestion to roll your own exception, but the text of the exception should clarify that the problem is in the argument list, not the individual argument values. I’d propose:

class BadCallError(ValueError):
    pass

Used when keyword arguments are missing that were required for the specific call, or argument values are individually valid but inconsistent with each other. ValueError would still be right when a specific argument is right type but out of range.

Shouldn’t this be a standard exception in Python?

In general, I’d like Python style to be a bit sharper in distinguishing bad inputs to a function (caller’s fault) from bad results within the function (my fault). So there might also be a BadArgumentError to distinguish value errors in arguments from value errors in locals.