简体   繁体   中英

python dictionary function calls with self values

In Python, how do I de-reference a dictionary's values in a call to a function referenced in that same dictionary?

For (silly) example:

def f1(x, y, z):
    return (x+y)/z

player = { 
    'x' : 0,
    'y' : 22,
    'z' : -37,
    'f' : f1(self.x, self.y, self.z)
}

I know can do this with classes. Sure. But, can do this with dictionaries?

You can't do that inside a literal because while the literal is evaluated the dictionary doesn't exist (yet). So there's no way to refer to it.

However, you can insert it later:

>>> player = { 'x' : 0, 'y' : 22, 'z' : -37}
>>> player['f'] = f1(player['x'], player['y'], player['z'])
>>> player
{'f': -0.5945945945945946, 'x': 0, 'y': 22, 'z': -37}

Or in case it should be dynamic, you could use a wrapper. For example a lambda function:

>>> player = { 'x' : 0, 'y' : 22, 'z' : -37}
>>> player['f'] = lambda: f1(player['x'], player['y'], player['z'])
>>> player['f']()
-0.5945945945945946
>>> player['x'] = 10
>>> player['f']()
-0.8648648648648649
>>> player['x'] = 100
>>> player['f']()
-3.2972972972972974

But I guess just making Player a class would be more readable and easier to maintain. Also classes make that sort of thing almost trivial without needing lambda s or such like.

def f1(x, y, z): return (x+y)/z

l = [10, 4, 7, f1]

l[3](l[0], l[1], l[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