Python:通过引用调用
我是python新手。有人能帮我理解python中的引用调用吗Python:通过引用调用,python,Python,我是python新手。有人能帮我理解python中的引用调用吗 #include <stdio.h> #include <conio.h> #include <malloc.h> void rd(float *a, int *n) { int i; for (i=1;i<= *n;i++) { printf("Enter element %d: ", i); scanf("%f", &
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
void rd(float *a, int *n)
{
int i;
for (i=1;i<= *n;i++) {
printf("Enter element %d: ",
i); scanf("%f", &a[i]);
}
}
float sum(float *a, int *n)
{
int i; float s=0;
for (i=1 ; i <= *n ; i++) s = s +
a[i]; return s;
}
int main(void)
{
int size; float *x, g;
printf("Give size of array: "); scanf("%d", &size);
x = (float *)malloc(size*sizeof(float)); // dynamic memory allocation
printf("\n");
rd(x, &size); // passing the addresses
g = sum(x, &size); // passing the addresses
printf("\nSum of elements = %f\n", g);
printf("\nDONE ! Hit any key ...");
getch(); return 0;
}
#包括
#包括
#包括
无效rd(浮点*a,整数*n)
{
int i;
例如(i=1;i在python中,无法传递“位置”(变量、数组元素、字典值或实例成员)的“地址”
提供其他代码更改位置的唯一方法是提供一个“路径”(例如变量名、数组和索引等)。作为一个非常奇怪的替代方法(Python中不经常使用),您可以传递一个“writer”函数来更改位置……例如:
def func(a, b, placeWriter):
placeWriter(a + b)
def caller():
mylist = [1, 2, 3, 4]
def writer(x):
mylist[3] = x
func(10, 20, writer)
更常见的是编写只返回所需值的函数;请注意,在Python中,返回多个值很简单,而在C中则不支持这一点,而是使用传递地址:
def func(): # void f(int *a, int *b, int *c) {
return 1, 2, 3 # *a=1; *b=2; *c=3;
# }
def caller(): # void caller() { int a, b, c;
a, b, c = func() # func(&a, &b, &c);
...
Python不支持按引用调用语义。但在这里几乎没有必要。Python的数据模型与C完全不同,而且按引用调用的概念实际上并不适合Python。您可能会发现这篇文章很有用:,它是由经验丰富的Ned Batchelder编写的。