简体   繁体   English

python 将参数传递给 function

[英]python passing parameter to a function

I am not clear about the concept of passing lists as arguments to functions in python.我不清楚将列表作为 arguments 传递给 python 中的函数的概念。

I've tried researching on this myself, didn't find adequate resources.我自己试过研究这个,没有找到足够的资源。

I want to implement a helper function which returns a number of random items from a given list.我想实现一个助手 function 从给定列表中返回许多随机项目。 (in django queryset) (在 django 查询集中)

However, the list may contain multiple rows and passing it by value to a function may result in an out of memory state, correct me if I'm wrong.但是,该列表可能包含多行并将其按值传递给 function 可能会导致 memory state 超出,如果我错了,请纠正我。

How then should I pass a list to a function?那么我应该如何将列表传递给 function?

In Python, there are names and values.在 Python 中有名称和值。 An assignment statement makes a name refer to a value.赋值语句使名称引用一个值。 An assignment never makes a copy, and assignment never changes a value.赋值永远不会复制,赋值永远不会改变值。 It only changes what value a name refers to.它只会更改名称所指的值。 Passing an argument to a function is like an assignment: now the local name of the argument in the function refers to the value that was passed in, and copies are never made.将参数传递给 function 就像一个赋值:现在 function 中参数的本地名称指的是传入的值,并且永远不会复制。 This mechanism of names referring to values, and assignments changing which value names refer to, is the same for all objects in Python, regardless of their type.对于 Python 中的所有对象,无论其类型如何,这种名称引用值的机制以及更改值名称所引用的赋值都是相同的。

This gets confusing because of mutable and immutable values.由于可变和不可变的值,这变得令人困惑。 If you pass a mutable value (for example, a list) into a function, and change the value, then the caller's names that refer to that value will also see the changed value.如果您将可变值(例如,列表)传递给 function,并更改该值,则引用该值的调用者名称也将看到更改后的值。 If you pass an immutable value into a function (for example, a string or number), then the value cannot be changed by anyone.如果您将不可变值传递给 function(例如,字符串或数字),则任何人都无法更改该值。

Everything in Python is an identifier. Python 中的所有内容都是标识符。 For lists, you can think of the evaluation strategy as "call by reference".对于列表,您可以将评估策略视为“引用调用”。 It is actually named "call by sharing" .它实际上被命名为“共享调用”

No. Passing a list to a function does not have any impact in terms of memory.不会。将列表传递给 function 对 memory 没有任何影响。 Python does not copy the list. Python复制列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM