python function *args and **kwargs with other specified keyword arguments

前端 未结 3 618
别那么骄傲
别那么骄傲 2021-02-07 15:31

I have a Python class with a method which should accept arguments and keyword arguments this way

class plot:
    def __init__(self, x, y):
        self.x = x
            


        
相关标签:
3条回答
  • 2021-02-07 16:19

    Here's a slight tweek to Jure C.'s answer:

    def set_axis(self, *args, **kwargs):
        xlabel = kwargs.pop('xlabel', 'x')
        ylabel = kwargs.pop('ylabel', 'y')
    

    I changed get to pop to remove xlabel and ylabel from kwargs if present. I did this because the rest of the code in the original question contains a loop that is meant to iterate through all kwargs except for xlabel and ylabel.

    0 讨论(0)
  • 2021-02-07 16:28

    You would use a different pattern:

    def set_axis(self, *args, **kwargs):
        xlabel = kwargs.get('xlabel', 'x')
        ylabel = kwargs.get('ylabel', 'y')
    

    This allows you to use * and ** while keeping the fallback values if keyword arguments aren't defined.

    0 讨论(0)
  • 2021-02-07 16:28

    In Python 3 this works:

    Python 3.2.3 (default, Oct 19 2012, 19:53:16) 
    >>> def set_axis(self, *args, xlabel="x", ylabel="y", **kwargs):
    ...     print(args, xlabel, ylabel, kwargs)
    ... 
    >>> set_axis(None, "test1", "test2", xlabel="new_x", my_kwarg="test3")
    ('test1', 'test2') new_x y {'my_kwarg': 'test3'}
    >>> 
    
    0 讨论(0)
提交回复
热议问题