I'm making a program that can access data stored inside a class. So for example I have this class:
#!/usr/bin/env python
import shelve
cur_dir = '.'
class Person:
def __init__(self, name, score, age=None, yrclass=10):
self.name = name
self.firstname = name.split()[0]
try:
self.lastname = name.split()[1]
except:
self.lastname = None
self.score = score
self.age = age
self.yrclass = yrclass
def yrup(self):
self.age += 1
self.yrclass += 1
if __name__ == "__main__":
db = shelve.open('people.dat')
db['han'] = Person('Han Solo', 100, 37)
db['luke'] = Person('Luke Skywalker', 83, 26)
db['chewbacca'] = Person('Chewbacca', 100, 90901)
So using this I can call out a single variable like:
print db['luke'].name
But if I wanted to print all variables, I'm a little lost.
If I run:
f = db['han']
dir(f)
I get:
['__doc__', '__init__', '__module__', 'age', 'firstname', 'lastname', 'name', 'score', 'yrclass', 'yrup']
But I want to be able to print the actual data of those.
How can I do this?
Thanks in advance!
dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all declared and built-in variables.
To print all instances of a class with Python, we can use the gc module. We have the A class and we create 2 instances of it, which we assigned to a1 and a2 . Then we loop through the objects in memory with gc. get_objects with a for loop.
print db['han'].__dict__
Rather than using magic methods , Vars could be more preferable.
print(vars(db['han']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With