Print all variables in a class? - Python
Asked Answered
S

8

32

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!

Snafu answered 21/10, 2010 at 23:28 Comment(0)
E
56
print db['han'].__dict__
Epicene answered 21/10, 2010 at 23:38 Comment(1)
Which is actually equal to vars(db['han']), as it calls __dict__.Lasseter
A
30

Rather than using magic methods, vars could be more preferable.

print(vars(db['han']))
Antimonyl answered 8/9, 2016 at 7:38 Comment(0)
E
15
print(vars(objectName))

Output:
{'m_var1': 'val1', 'm_var2': 'val2'}

This will print all the class variables with values initialised.

Eggshaped answered 20/3, 2017 at 15:31 Comment(1)
Does it also print a list of all callable functions?Carlyncarlynn
P
4

Define __str__ or __repr__ methods in your Person class and print the object.

Password answered 21/10, 2010 at 23:41 Comment(0)
E
2

Just try beeprint

after pp(db['han']), it will print this:

instance(Person):
    age: 37
    firstname: 'Han',
    lastname: 'Solo',
    name: 'Han Solo',
    score: 100,
    yrclass: 10

no methods, no private properties.

Ehtelehud answered 16/9, 2016 at 15:44 Comment(0)
C
2

If you want a method to print all the attribute, you can use:

def get_attribute(self):
    """
    Prints all attribute of object
    """

    for i in (vars(self)):
        print("{0:10}: {1}".format(i, vars(self)[i]))
    

You then need to call the method:

db['luke'].get_attribute()

and it will print:

name      : Luke Skywalker 
firstname : Luke 
lastname  : Skywalker 
score     : 83 
age       : 26 
yrclass   : 10

Please note you can play around with the value {0:10} to change the spacing for the columns.

Conic answered 10/11, 2022 at 11:30 Comment(0)
D
0

print(vars(self)) or pprint(vars(self))

and to access self.variable name

Eg. self._own_name

Discriminating answered 2/1, 2021 at 10:32 Comment(0)
S
0

If you want only the values of the variables you defined, you can do:

variables = [v for k, v in db['han'].__dict__.items() 
              
              # variable is not a python internal variable
              if not k.startswith("__") 
              and not k.endswith("__")
              
              # and is not a function
              and not "method" in str(v)
              and not "function" in str(v)]


print(variables) 
# ['Han Solo', 'Han', 'Solo', 100, 37, 10]

You will not print functions or internal Python variables (start and end with __), called dunders.

Shore answered 8/5, 2022 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.