Why are default values ​​shared between objects in Python?

王林
Release: 2023-08-20 19:33:23
forward
1121 people have browsed it

Why are default values ​​shared between objects in Python?

The concept of default values ​​in Python is based on using mutable or immutable objects. In programming practice, it is best not to use mutable objects as default values. Instead, use None as the default value to avoid problems. Immutable objects, such as numbers, strings, tuples, and None, do not change. For mutable objects such as dictionaries, lists, and class instances, changes can cause confusion.

Let's look at an example of a dictionary in a function and what's wrong with it and how to fix it.

question

We have a function. In this function, we have a dictionary as parameter and set the default value. The first time this function is called, mydict contains only one item. On the second call, mydict contains two items because when foo() started executing, mydict already had one item.

def foo(mydict={}):
   ... calculate...
   mydict[key] = value
   return mydict
Copy after login

We often expect function calls to create new objects with default values. However, it is not. Default values ​​are only created once when the function is defined. If the object is modified, as in the dictionary example above, subsequent calls to the function will reference the modified object.

solution

To solve the problem of using mutable objects as default values, like this -

def foo(mydict={}):
   ...
Copy after login

Use immutable objects, such as None -

def foo(mydict=None):
   if mydict is None:
      mydict = {}
Copy after login

When you have a function that is computationally expensive, one technique is to cache the argument and result values ​​for each call to the function, and return the cached values ​​when the same values ​​are requested again.

This is called memoization and can be achieved like this -

# Callers can only provide two parameters and optionally pass _cache by keyword
def expensive(arg1, arg2, *, _cache={}):
   if (arg1, arg2) in _cache:
      return _cache[(arg1, arg2)]

  # Calculate
  result = ... expensive computation ...
  _cache[(arg1, arg2)] = result
  return result
Copy after login

The following will store the results in the cache −

_cache[(arg1, arg2)] = result
Copy after login

The above is the detailed content of Why are default values ​​shared between objects in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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