-1

When doing a method call in Python, in which cases do you use the = sign when entering arguments?

I noticed sometimes it's:

object.method(argument1 = ... , argument2 = ...)

and other times it's

object.method(... , ...)

Thanks in advance!

Barmar
  • 741,623
  • 53
  • 500
  • 612
johannes
  • 23
  • 2
  • These are named arguments versus positional arguments. It's not specific to method calls, you can do it with ordinary functions as well. – Barmar Nov 12 '20 at 08:35
  • 3
    https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments – Masklinn Nov 12 '20 at 08:35
  • They should be explained in most Python tutorials. – Barmar Nov 12 '20 at 08:35
  • You can use them (a) for just being more explicit, (b) for skipping optional parameters, e.g. calling `def f(a, b=1, c=2)` as `f(42, c=3)`, or (c) for entirely unspecific `**kwargs`. You example seems to be case (a). – tobias_k Nov 12 '20 at 08:37
  • Does this answer your question? [Positional argument vs named keyword argument](https://stackoverflow.com/questions/9450656/positional-argument-v-s-keyword-argument#:~:text=Positional%20arguments%20are%20arguments%20that,must%20passed%20to%20the%20function.&text=In%20python%20optional%20arguments%20are%20arguments%20that%20have%20a%20default%20value.) – Nastor Nov 12 '20 at 08:38

1 Answers1

2

That types of arguments are called keyword arguments, probably you've seen that as (kwargs). In a function you can pass 2 types of args, positional arguments and keyword-arguments. def function(arg): So you have to pass inside this function a positional argument, this means that you have to pass only the value for that arg like function(1) or maybe a string function("hello") or maybe a list and so on; This type of arg is called position arg. When you have to specify the name of the variable inside the brackets of a function call like function(name = "John"), you are using the keyword args. If you want to understand more on this topic, i suggest you to see the unpack operator in Python (*) and then *args and **kwargs. 2 words to say what *args and **kwargs do in Python, they allows you to specify an unlimited number of arguments inside a function call.

def function(*args, **kwargs):
   pass
function(1,2,3,"hello",[1,2,3],name="John",age=5)
RockySTBL
  • 36
  • 1