xiaochuan 发表于 2017-4-23 07:52:00

Python Function parameters

  A note on the Function Argument.
  


# about the parameter of the python argument
# there are 4 types of argument that a Python Fucntino that can accept
# they are
#   1. fixed argument (or called non-default argument)
#   2. the positional arguments
#   3. the keyword arguments
#   4. the default arguments ( a special case of keyword argument)
#
# the syntax to define python function is as follow
#    func_name(a, b, ..., [*args | default=default_values]], **kwargs)
#
#so the general rule of defining python argument is as follow
#      def func_name(a, b, ..., *args, **kwargs)
# however, it is quite confusing when the default value for a argument comes into the play
# to declare a default argument, you normally do this
#      def func_name(a, b, ..., *args, default=default_value)
# because the default value for an argument syntactically looks like the keyword argument
# which means
#    1. you cannot have default argument before the positional argument
#      def func_name(a, b, ..., default=default_value, *args) # raise TypeError
#    2. it is not allowed if to have default argument in the middle of fixed argument
#      def func_name(a, ..., default=default_value, b, ..., *args) # raise TypeError
#    3. you cannot have both positional argument and default argument together...
#      def func_name(a, b, *args, default="default_value") # raise TypeError
#      def func_name(a, b, default=default_value", *args, **kwargs) # raise TypeError
#    4. You can have an argument with default value after the positional argument and before the
#       keyword argument (**kwargs) (you can think default valued argument is a special form of
#       keyword argument.
#         def func_name(a, b, ..., default=default_value, **kwargs)
#    5. As said in 4, if you try to put the default argument after the keyword arguments, it fails
#         def func_name(a, b, ..., **kwargs, default=default_value);

def could_compile1(a, b, default="default_value", **kwargs):
print a, b
print default
for key in kwargs:
print("keyword argument {0} = {1}".format(key, kwargs))
def would_fail(a, default="default_value", b, *args):
pass

def would_fail2(a, b, default="default_value", *args):
pass

#def would_fail3(a, b,*args, default="default_value", **kwargs):
#    pass
#def would_fail4(a, b, default="default_value", *args, **kwargs):
#    pass
#def would_fail5(a, b, **kwargs, default="default_value"):
#    pass

def main():
could_compile1(1, 2, default="overriden default value", optional1="optional 1 value", optional2="optional 2 value")
# would_compile2(1, "override_default_value", 2, 3, 4) # SyntaxError: non-default argument follows default argument
# would_fail2(1, 2, "override_default_value", 3, 4) # SyntaxError: non-default argument follows default argument
pass
 
页: [1]
查看完整版本: Python Function parameters