从另一个函数更改函数中的局部变量

时间:2015-10-06 19:48:36

标签: python function variables scope

首先,这是我的示例代码:

编辑:我应该在我的实际代码中指定that_func()已经返回另一个值,所以我希望它返回一个值,并且另外更改c

编辑2:编辑代码以显示我的意思

def this_func():
    c=1   # I want to change this c
    d=that_func()
    print(c, d)

def that_func():
     this_func.c=2 #Into this c, from this function
     return(1000) #that_func should also return a value

this_func()

我想要做的是将this_func()中的局部变量c更改为我在that_func()中指定的值,以便它打印2而不是1。

根据我在网上收集的内容, this_func.c = 2 应该这样做,但它不起作用。我做错了什么,还是我误解了?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

是的,你误解了。

<?php global $post; $categories = get_the_category(); foreach ($categories as $category) :?> <ul> <?php $posts = get_posts('numberposts=3&category='. $category->term_id); foreach($posts as $post) : ?> <li> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </li> <?php endforeach; ?> <?php endforeach; ?> </ul> 不是functions。您无法像class那样访问function的变量。

显然,它不是最聪明的代码,但是这段代码应该让我们知道如何使用函数的变量。

def this_func():
    c=1   # I want to change this c
    c=that_func(c) # pass c as parameter and receive return value in c later
    print(c)

def that_func(b): # receiving value of c from  this_func()
    b=2  # manipulating the value
    return b #returning back to this_func()

this_func()

答案 1 :(得分:0)

将其包裹在对象中并将其传递给that_func

def this_func():
    vars = {'c': 1}
    d = that_func(vars)
    print vars['c'], d

def that_func(vars):
    vars['c'] = 2
    return 1000

或者,您可以将其作为常规变量传递,that_func可以返回多个值:

def this_func():
    c = 1
    c, d = that_func(c)
    print c, d

def that_func(c):
    c = 2
    return c, 1000
相关问题