打印一个类中的所有变量?- Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3992803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:44:28  来源:igfitidea点击:

Print all variables in a class? - Python

pythonclassshelve

提问by Fergus Barker

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!

提前致谢!

采纳答案by DisplacedAussie

print db['han'].__dict__

回答by EMPraptor

Define __str__or __repr__methods in your Person class and print the object.

在 Person 类中定义__str____repr__方法并打印对象。

回答by Suresh2692

Rather than using magic methods, Varscould be more preferable.

与使用魔法方法相比Vars可能更可取。

print(vars(db['han']))

回答by Anyany Pan

Just try beeprint

试试beeprint

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

之后pp(db['han']),它将打印:

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

no methods, no private properties.

没有方法,没有私有属性。

回答by Archie Yalakki

print(vars(objectName))

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

This will print all the class variables with values initialised.

这将打印所有具有初始化值的类变量。