17 Jul, 2009, Confuto wrote in the 1st comment:
Votes: 0
I'm fairly new to Python (read: started using it a couple of weeks ago) and have been using it to fiddle around with NakedMUD. I've run into issues with my vital statistics system, though, and I figure it's more an issue with my knowledge of Python than my use of NakedMUD, hence why I'm asking this question here.

Current function:
def getVital(ch, vital):
if vital == "blood":
return ch.aux("vitals_aux").blood['cur']
elif vital == "sanity":
return ch.aux("vitals_aux").sanity['cur']
elif vital == "energy":
return ch.aux("vitals_aux").energy['cur']
elif vital == "will":
return ch.aux("vitals_aux").will['cur']
else:
return 0

Essentially, I want the above function but in this form:
def getVital(ch, vital):
return ch.aux("vitals_aux").vital['cur']

However using that returns an error, as there's no "vital" dictionary stored in the character's auxiliary data (a NakedMUD thing).

I'm almost certain this is a result of me using the language wrong, so I was wondering if there's something I can use to "expand"
ch.aux("vitals_aux").vital['cur']

and replace that single instance of "vital" with whatever is stored in the variable "vital".

Thanks!
17 Jul, 2009, hollis wrote in the 2nd comment:
Votes: 0
I think this should work:

def getVital(ch, vital):
return eval("ch.aux('vitals_aux')." + vital + "['cur']")
17 Jul, 2009, David Haley wrote in the 3rd comment:
Votes: 0
Python distinguishes between attributes and "items" in an object. A dictionary maps items to values, which is done using square bracket notation, whereas attributes are not as easy to access programmatically.

One solution is to use evals as hollis showed, but this suffers from several issues. For one it's not efficient, for two it has a security risk (what if arbitrary code sneaks into the 'vital' variable and you start executing it?).

The proper solution for programmatic lookup of attributes is getattr:

vital_map = getattr(ch.aux('vitals_aux'), vital)
return vital_map['cur']

One thing I like about Lua is that a.b is exactly the same as a['b'] – there is no distinction made between attributes and table entries.
17 Jul, 2009, Idealiad wrote in the 4th comment:
Votes: 0
One thing to keep in mind is that every Python object instance holds a dictionary of its attributes.

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(object):
… def __init__(self):
… self.foo = 'bar'
… self.vitals = {'str' : 10, 'int' : 11, 'dex' : 14}

>>> a = A()
>>> a.__dict__
{'foo': 'bar', 'vitals': {'int': 11, 'dex': 14, 'str': 10}}
>>> a.__dict__['vitals']['str']
10
>>>
18 Jul, 2009, Confuto wrote in the 5th comment:
Votes: 0
Thanks a lot for the responses, they helped me out a great deal. I ended up going the getattr/setattr route - may as well use a function designed for this sort of thing, eh?
0.0/5