Confuto
Conjurer


Group: Members
Posts: 115
Joined: Nov 1, 2008
|
#1 id:29047 Posted Jul 17, 2009, 2:57 am
|
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:
Code (text): 1
2
3
4
5
6
7
8
9
10
11
12
13 | 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:
Code (text): 1
2
3
4 | 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"
Code (text): 1
2
3 | ch.aux("vitals_aux").vital['cur'] |
and replace that single instance of "vital" with whatever is stored in the variable "vital".
Thanks!
|
|
|
hollis
Apprentice

Group: Members
Posts: 16
Joined: Jan 24, 2009
|
#2 id:29059 Posted Jul 17, 2009, 3:56 am
|
I think this should work:
Code (text): 1
2
3
4
5
6 |
def getVital(ch, vital):
return eval("ch.aux('vitals_aux')." + vital + "['cur']")
|
|
|
|
|
|
Idealiad
Sorcerer

Group: Members
Posts: 388
Joined: Jan 28, 2007
|
#4 id:29079 Posted Jul 17, 2009, 10:57 am
|
One thing to keep in mind is that every Python object instance holds a dictionary of its attributes.
Code (text): 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 |
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
>>>
|
|
|
|
Confuto
Conjurer


Group: Members
Posts: 115
Joined: Nov 1, 2008
|
#5 id:29098 Posted Jul 17, 2009, 9:22 pm
|
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?
|
|
|