-2

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).

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119
  • 1
    Possible duplicate of [What does \*\* (double star/asterisk) and \* (star/asterisk) do for parameters?](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) – Alec Mar 08 '19 at 04:57

3 Answers3

1
def foo(self, *args):

Yes, that is correct.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

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)
Community
  • 1
  • 1
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
1

You declared the method correctly. You can also use double asterisks to accept keyword arguments. Reference: Expressions

A double asterisk ** denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.

....

An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.

Args will be a tuple. To access the values you will have to iterate or use positional arguments, ie: args[0]

Community
  • 1
  • 1
ap288
  • 41
  • 5