I’m making a program that can access data stored inside a class. So for example I have this class:
JavaScript
x
27
27
1
#!/usr/bin/env python
2
import shelve
3
4
cur_dir = '.'
5
6
class Person:
7
def __init__(self, name, score, age=None, yrclass=10):
8
self.name = name
9
self.firstname = name.split()[0]
10
try:
11
self.lastname = name.split()[1]
12
except:
13
self.lastname = None
14
15
self.score = score
16
self.age = age
17
self.yrclass = yrclass
18
def yrup(self):
19
self.age += 1
20
self.yrclass += 1
21
22
if __name__ == "__main__":
23
db = shelve.open('people.dat')
24
db['han'] = Person('Han Solo', 100, 37)
25
db['luke'] = Person('Luke Skywalker', 83, 26)
26
db['chewbacca'] = Person('Chewbacca', 100, 90901)
27
So using this I can call out a single variable like:
JavaScript
1
2
1
print db['luke'].name
2
But if I wanted to print all variables, I’m a little lost.
If I run:
JavaScript
1
3
1
f = db['han']
2
dir(f)
3
I get:
JavaScript
1
2
1
['__doc__', '__init__', '__module__', 'age', 'firstname', 'lastname', 'name', 'score', 'yrclass', 'yrup']
2
But I want to be able to print the actual data of those.
How can I do this?
Thanks in advance!
Advertisement
Answer
JavaScript
1
2
1
print db['han'].__dict__
2