Search code examples
pythonargs

How to use *args and self in Python constructor


I need a Python method to have access to self for instance variables and also be able to take any number of arguments. I basically want a method foo that can be called via

foo(a, b, c)

or

foo()

In the class, I think the constructor would be

def foo(self, *args):

Is this correct? Also, fyi, I am new to Python (if you can't tell).


Solution

  • You just have to add it after the self parameter:

    class YourClass:
        def foo(self, *args):
            print(args)
        def bar(self, *args, **kwargs):
            print(args)
            print(kwargs)
        def baz(self, **kwargs):
            print(kwargs)
    

    I have also added a method in which you also add **kwargs, and the case in which you add both *args and **kwargs.

    Examples

    >>> o = YourClass()
    >>> o.foo()
    ()
    >>> o.foo(1)
    (1,)
    >>> o.foo(1, 2)
    (1, 2)