CPP手艺人

导航切换

联系电话:
18123279828

CPP手艺人
当前位置:
主页
> 整站优化

python如何打印对象的属性值

作者:CPP手艺人 来源: CPP手艺人   日期:2026-12-01 18:21:55

在Python中,何打(da)可以使用dir()函数(shu)和getattr()函数来打印对象的印对属性值。dir()函数可以列出对象的属性所有属性和方法,getattr()函数可以根据属性名获取属性值。何打(da)(图片来源网络,印对侵删)

以下(xia)是(shi)属性(xing)一个简单的示例:

python如何打印对象的属性值

class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print(f"Hello, my name is { self.name} and I am { self.age} years old.")创建一个(ge)Person对象person = Person("张(zhang)三", 30)使(shi)用dir()函数列出对象的所有属性和方法attributes = dir(person)使用单元表格打印属性名(ming)和属性值print("属性名t属性值")for attribute in attributes: if not attribute.startswith("__"): # 过滤掉内置属性和方法 value = getattr(person, attribute) print(f"{ attribute}t{ value}")

输出结(jie)果:

python如何打印对象的属性值

属性名 属性值age 30name 张三say_hello <bound method Person.say_hello of <__main__.Person object at 0x7f8c1c2d3a90>>

在这个示(shi)例中(zhong),我们定义了一个Person类,何打然后创建了(le)一个Person对象,印对接着,属性我们使用(yong)dir()函数列出对象的何打所有属性和方法,然后(hou)使用getattr()函数获取每个属性(xing)的(de)印对值(zhi),并使用单元表格打印出来,属性注意,何打我们过(guo)滤掉了以双下划线开头的印对内置属性和方法。

python如何打印对象的属性值

属性