Home  >  Article  >  Backend Development  >  How to write a function with output parameters (called by reference) in Python?

How to write a function with output parameters (called by reference) in Python?

WBOY
WBOYforward
2023-09-02 16:21:06938browse

How to write a function with output parameters (called by reference) in Python?

All parameters (arguments) in the Python language are passed by reference. This means that if you change the reference content of a parameter in a function, that change will also be reflected in the calling function.

Achieve this by -

Return result tuple

Example

In this example we will return a tuple of results -

# Function Definition
def demo(val1, val2):
   val1 = 'new value'
   val2 = val2 + 1
   return val1, val2

x, y = 'old value', 5

# Function call
print(demo(x, y))

Output

('new value', 6)

Passing mutable objects

Example

In this example we will pass a mutable object -

# Function Definition
def demo2(a):
   # 'a' references a mutable list
   a[0] = 'new-value'
   # This changes a shared object
   a[1] = a[1] + 1

args = ['old-value', 5]
demo2(args)
print(args)

Output

['new-value', 6]

Pass a mutated dictionary

Example

In this example we will pass a dictionary -

def demo3(args):
   # args is a mutable dictionary
   args['val1'] = 'new-value'
   args['val2'] = args['val2'] + 1

args = {'val1': 'old-value', 'val2': 5}

# Function call
demo3(args)
print(args)

Output

{'val1': 'new-value', 'val2': 6}

Values ​​in class instances

Example

In this example we will pack the value in the class instance -

class Namespace:
   def __init__(self, **args):
      for key, value in args.items():
         setattr(self, key, value)

def func4(args):
   # args is a mutable Namespace
   args.val1 = 'new-value'
   args.val2 = args.val2 + 1

args = Namespace(val1='old-value', val2=5)

# Function Call
func4(args)
print(vars(args))

Output

{'val1': 'new-value', 'val2': 6}

The above is the detailed content of How to write a function with output parameters (called by reference) in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete