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

发布于 2024-09-28 13:06:28 字数 1089 浏览 3 评论 0原文

我正在制作一个可以访问存储在类中的数据的程序。例如,我有这个类:

#!/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)

所以使用这个我可以调用一个变量,例如:

print db['luke'].name

但如果我想打印所有变量,我就有点迷失了。

如果我运行:

f = db['han']
dir(f)

我得到:

['__doc__', '__init__', '__module__', 'age', 'firstname', 'lastname', 'name', 'score', 'yrclass', 'yrup']

但我希望能够打印这些的实际数据。

我该怎么做?

提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

孤独患者 2024-10-05 13:06:28
print db['han'].__dict__
print db['han'].__dict__
埋情葬爱 2024-10-05 13:06:28

而不是使用魔术方法vars 可能更可取。

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

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

print(vars(db['han']))
吻泪 2024-10-05 13:06:28
print(vars(objectName))

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

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

print(vars(objectName))

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

This will print all the class variables with values initialised.

风筝在阴天搁浅。 2024-10-05 13:06:28

定义 __str____repr__ 方法并打印对象。

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

熟人话多 2024-10-05 13:06:28

尝试 beeprint

只要在 pp(db['han']) 之后 ,它就会打印:

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

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

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.

嘿嘿嘿 2024-10-05 13:06:28

如果您想要一个方法来打印所有属性,您可以使用:

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

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

然后您需要调用该方法:

db['luke'].get_attribute()

它会打印:

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

请注意,您可以使用值 {0:10} 来更改列的间距。

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.

老旧海报 2024-10-05 13:06:28

打印(变量(自身))
或者
pprint(vars(self))

并访问 self.variable 名称

例如。 self._own_name

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

and to access self.variable name

Eg. self._own_name

淡淡绿茶香 2024-10-05 13:06:28

如果您只需要定义的变量的值,您可以这样做:

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]

您不会打印函数或内部 Python 变量(以 __ 开头和结尾),称为 dunders

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文