Python中,遍历属性列表可以通过使用内置函数dir()
和getattr()
来实现。
dir()
函数返回一个包含对象所有属性和方法名称的列表。可以将这个列表作为遍历的目标,然后使用getattr()
函数获取每个属性的值。
以下是一个示例代码:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
# 使用dir()函数获取属性列表
attributes = dir(person)
# 遍历属性列表并获取属性值
for attribute in attributes:
value = getattr(person, attribute)
print(f"{attribute}: {value}")
输出结果将会是:
__class__: <class '__main__.Person'>
__delattr__: <method-wrapper '__delattr__' of Person object at 0x7f8a2c3b7a90>
__dict__: {'name': 'Alice', 'age': 25}
__dir__: <built-in method __dir__ of Person object at 0x7f8a2c3b7a90>
__doc__: None
__eq__: <method-wrapper '__eq__' of Person object at 0x7f8a2c3b7a90>
__format__: <built-in method __format__ of Person object at 0x7f8a2c3b7a90>
__ge__: <method-wrapper '__ge__' of Person object at 0x7f8a2c3b7a90>
__getattribute__: <method-wrapper '__getattribute__' of Person object at 0x7f8a2c3b7a90>
__gt__: <method-wrapper '__gt__' of Person object at 0x7f8a2c3b7a90>
__hash__: <method-wrapper '__hash__' of Person object at 0x7f8a2c3b7a90>
__init__: <bound method Person.__init__ of <__main__.Person object at 0x7f8a2c3b7a90>>
__init_subclass__: <built-in method __init_subclass__ of type object at 0x557e8e4e4f50>
__le__: <method-wrapper '__le__' of Person object at 0x7f8a2c3b7a90>
__lt__: <method-wrapper '__lt__' of Person object at 0x7f8a2c3b7a90>
__module__: __main__
__ne__: <method-wrapper '__ne__' of Person object at 0x7f8a2c3b7a90>
__new__: <built-in method __new__ of type object at 0x557e8e4e4f50>
__reduce__: <built-in method __reduce__ of Person object at 0x7f8a2c3b7a90>
__reduce_ex__: <built-in method __reduce_ex__ of Person object at 0x7f8a2c3b7a90>
__repr__: <method-wrapper '__repr__' of Person object at 0x7f8a2c3b7a90>
__setattr__: <method-wrapper '__setattr__' of Person object at 0x7f8a2c3b7a90>
__sizeof__: <built-in method __sizeof__ of Person object at 0x7f8a2c3b7a90>
__str__: <method-wrapper '__str__' of Person object at 0x7f8a2c3b7a90>
__subclasshook__: <built-in method __subclasshook__ of type object at 0x557e8e4e4f50>
__weakref__: None
age: 25
name: Alice
在这个例子中,我们定义了一个Person
类,它有name
和age
两个属性。我们创建了一个Person
对象,并使用dir()
函数获取属性列表。然后,我们使用getattr()
函数遍历属性列表,并获取每个属性的值进行打印。
需要注意的是,dir()
函数返回的列表中包含了一些特殊属性和方法,如__class__
、__dict__
、__doc__
等。这些属性和方法是Python对象的内置属性和方法,不是我们自定义的属性。
领取专属 10元无门槛券
手把手带您无忧上云