要打印对象的所有属性,可以使用Python内置的dir()函数。这个函数会返回一个包含对象所有属性和方法的列表。你可以将这个列表打印出来,或者使用循环打印每个属性。
例如:
class Person: def __init__(self, name, age): self.name = name self.age = ageperson = Person("Alice", 30)# 打印对象所有属性print(dir(person))# 使用循环打印每个属性for attribute in dir(person): if not attribute.startswith("__"): print(attribute, getattr(person, attribute))运行这段代码,你会看到对象person的所有属性被打印出来。注意,dir()函数返回的列表中包含了一些特殊方法和属性,例如__init__、__str__等,你可以通过判断属性名是否以双下划线开头来排除这些特殊属性。




