简体   繁体   中英

Python references to references in python

I have a function that takes given initial conditions for a set of variables and puts the result into another global variable. For example, let's say two of these variables is x and y. Note that x and y must be global variables (because it is too messy/inconvenient to be passing large amounts of references between many functions).

x = 1
y = 2

def myFunction():
    global x,y,solution
    print(x)
    < some code that evaluates using a while loop >
    solution = <the result from many iterations of the while loop>

I want to see how the result changes given a change in the initial condition of x and y (and other variables). For flexibility and scalability, I want to do something like this:

varSet = {'genericName0':x, 'genericName1':y} # Dict contains all variables that I wish to alter initial conditions for
R = list(range(10))
for r in R:
    varSet['genericName0'] = r    #This doesn't work the way I want...
    myFunction()

Such that the 'print' line in 'myFunction' outputs the values 0,1,2,...,9 on successive calls.

So basically I'm asking how do you map a key to a value, where the value isn't a standard data type (like an int) but is instead a reference to another value? And having done that, how do you reference that value?

If it's not possible to do it the way I intend: What is the best way to change the value of any given variable by changing the name (of the variable that you wish to set) only?

I'm using Python 3.4, so would prefer a solution that works for Python 3.

EDIT: Fixed up minor syntax problems.

EDIT2: I think maybe a clearer way to ask my question is this:

Consider that you have two dictionaries, one which contains round objects and the other contains fruit. Members of one dictionary can also belong to the other (apples are fruit and round). Now consider that you have the key 'apple' in both dictionaries, and the value refers to the number of apples. When updating the number of apples in one set, you want this number to also transfer to the round objects dictionary, under the key 'apple' without manually updating the dictionary yourself. What's the most pythonic way to handle this?

Instead of making x and y global variables with a separate dictionary to refer to them, make the dictionary directly contain "x" and "y" as keys.

varSet = {'x': 1, 'y': 2}

Then, in your code, whenever you want to refer to these parameters, use varSet['x'] and varSet['y'] . When you want to update them use varSet['x'] = newValue and so on. This way the dictionary will always be "up to date" and you don't need to store references to anything.

we are going to take an example of fruits as given in your 2nd edit:

def set_round_val(fruit_dict,round_dict):
    fruit_set = set(fruit_dict)
    round_set = set(round_dict)
    common_set = fruit_set.intersection(round_set) # get common key
    for key in common_set:
        round_dict[key] = fruit_dict[key] # set modified value in round_dict
    return round_dict

fruit_dict = {'apple':34,'orange':30,'mango':20}
round_dict = {'bamboo':10,'apple':34,'orange':20} # values can even be same as fruit_dict
for r in range(1,10):
    fruit_set['apple'] = r
    round_dict = set_round_val(fruit_dict,round_dict)
    print round_dict

Hope this helps.

From what I've gathered from the responses from @BrenBarn and @ebarr, this is the best way to go about the problem (and directly answer EDIT2).

Create a class which encapsulates the common variable:

class Count:
    __init__(self,value):
        self.value = value

Create the instance of that class:

import Count
no_of_apples = Count.Count(1)
no_of_tennis_balls = Count.Count(5)
no_of_bananas = Count.Count(7)

Create dictionaries with the common variable in both of them:

round = {'tennis_ball':no_of_tennis_balls,'apple':no_of_apples}
fruit = {'banana':no_of_bananas,'apple':no_of_apples}

print(round['apple'].value) #prints 1
fruit['apple'].value = 2
print(round['apple'].value) #prints 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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