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

WBOY
Release: 2023-09-02 16:21:06
forward
897 people have browsed it

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))
Copy after login

Output

('new value', 6)
Copy after login

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)
Copy after login

Output

['new-value', 6]
Copy after login

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)
Copy after login

Output

{'val1': 'new-value', 'val2': 6}
Copy after login
Copy after login

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))
Copy after login

Output

{'val1': 'new-value', 'val2': 6}
Copy after login
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!