By default, initialization of marked variables in a function definition

It is well known that in order to set the default value for a variable inside a function in Python, the following syntax is used:

def func(x = 0):
    if x == 0:
        print("x is equal to 0")
    else:
        print("x is not equal to 0")

So, if the function is called as such:

>>> func()

The result is

'x is equal to 0'

But when a similar method is used for marked variables, for example,

def func(*x = (0, 0)):

this leads to a syntax error. I tried to enable the syntax by doing (*x = 0, 0), but the same error occurs. Is it possible to initialize a marked variable with a default value?

+4
source share
2 answers

,

* - ( args)

** - ( kwargs)

, , . , .

def arg_test(*args,**kwargs):
   if not args:
      print "* not args provided set default here"
      print args
   else:
      print "* Positional Args provided"
      print args


   if not kwargs:
      print "* not kwargs provided set default here"
      print kwargs
   else:
      print "* Named arguments provided"
      print kwargs

#no args, no kwargs
print "____ calling with no arguments ___"
arg_test()

#args, no kwargs
print "____ calling with positional arguments ___"
arg_test("a", "b", "c")

#no args, but kwargs
print "____ calling with named arguments ___"
arg_test(a = 1, b = 2, c = 3)
+2

, , (). - , (tl; dr: Python , , ; , , PEP 3132: https://www.python.org/dev/peps/pep-3132/) , , x . :

def func(*x):
    if x == ():  # Check if x is an empty tuple
        x = (0, 0)
    if x == 0:
        print("x is equal to 0")
    else:
        print("x is not equal to 0")
+2

Source: https://habr.com/ru/post/1664234/


All Articles