首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python -遍历属性列表

Python中,遍历属性列表可以通过使用内置函数dir()getattr()来实现。

dir()函数返回一个包含对象所有属性和方法名称的列表。可以将这个列表作为遍历的目标,然后使用getattr()函数获取每个属性的值。

以下是一个示例代码:

代码语言:txt
复制
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}")

输出结果将会是:

代码语言:txt
复制
__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类,它有nameage两个属性。我们创建了一个Person对象,并使用dir()函数获取属性列表。然后,我们使用getattr()函数遍历属性列表,并获取每个属性的值进行打印。

需要注意的是,dir()函数返回的列表中包含了一些特殊属性和方法,如__class____dict____doc__等。这些属性和方法是Python对象的内置属性和方法,不是我们自定义的属性。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

Python Python中的反射机制

概念 借用java中的定义:在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性 module2.py #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' class TestClass: def __init__(self): pass def fun(self): pass module1.py 1、不导入模块 #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' if __name__ == '__main__': print(globals()) 运行结果 运行结果: {'__author__': 'shouke', '__loader__': <_frozen_importlib.SourceFileLoader object at 0x01F5C310>, '__name__': '__main__', '__builtins__': , '__package__': None, '__doc__': None, '__cached__': None, '__file__': 'F:/project/interface_project/module1.py'} 说明:globals函数返回一个map,map中的key是全局范围内对象的名字,value是该对象的实例 2、导入模块 修改module1.py代码如下 #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' import sys if __name__ == '__main__': print(globals()) 运行结果: {'__loader__': <_frozen_importlib.SourceFileLoader object at 0x01D9C310>, 'sys': , '__package__': None, '__builtins__': , '__author__': 'shouke', '__name__': '__main__', '__doc__': None, '__file__': 'F:/project/interface_project/module1.py', '__cached__': None} 如上,新增了带颜色部分的内容 3.导入类 修改module1.py代码如下 #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' from module2 import TestClass if __name__ == '__main__': print(globals()) 输出结果: {'TestClass': , '__package__': None, '__doc__': None, '__file__': 'F:/project/interface_project/module1.py', '__cached__': None, '__builtins__': , '__loader__': <_frozen_importlib.SourceFileLoader object at 0x01DFC310>, '__author__': 'shouke', '__name__': '__main__'} 如上,新增了带颜色部分的内容 4、结合getattr,callable函数 #!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' from module2 import TestClass if __name__ == '__main__': # 动态获取类 print('动态获取类:%s'% globals()['TestClass']) print('\n') # 获取类的属性和函数 print(dir(TestClass)) print('\n') print(getattr(TestClass,'fun')) # 获取类的函数对象 print(getattr(globals()['TestClass'](),'attr')) # 获取类实例的属性对象print('\n') print(callable(getattr(TestClass,'fun'))) # 查看类的函数对象是否

01
领券