Python中的反射与内省允许代码察觉和修改它自己。反射指的是程序在运行时可以访问、检测和修改它自己的结构或行为的一种能力。而内省则更侧重于查看对象的类型和属性,比如查看一个对象是否有某个属性或方法,以及查看对象的文档字符串等。本文将深入探讨Python的反射与内省能力。

一、基础的反射函数
Python提供了许多内置函数来支持反射。比如type,id,getattr,setattr和hasattr等。
class MyClass:
    def __init__(self):
        self.my_attribute = 123
        self.another_attribute = "Hello"
        
    def my_method(self):
        pass
instance = MyClass()
# 使用type检测对象类型
print(type(instance))  # 输出: <class '__main__.MyClass'>
# 使用id获取对象内存地址
print(id(instance))  
# 使用getattr获取属性值
print(getattr(instance, 'my_attribute'))  # 输出: 123
# 使用setattr修改属性值
setattr(instance, 'my_attribute', 456)
print(getattr(instance, 'my_attribute'))  # 输出: 456
# 使用hasattr检测是否有某个属性
print(hasattr(instance, 'nonexistent_attribute'))  # 输出: False
二、dir函数和__dir__方法
dir函数和__dir__方法可以用来获取一个对象的所有属性和方法。
class MyClass:
    def __init__(self):
        self.my_attribute = 123
    def my_method(self):
        pass
instance = MyClass()
print(dir(instance))
输出将包含my_attribute和my_method,以及一些由Python自动添加的魔法方法。
三、反射在动态操作中的应用
反射在需要进行动态操作时非常有用,比如我们可以基于字符串的名字来调用方法:
class MyClass:
    def my_method(self):
        return "Hello, world!"
instance = MyClass()
method_name = 'my_method'
method = getattr(instance, method_name)
print(method())  # 输出: Hello, world!
四、内省的一些有用工具
Python标准库提供了一些用于内省的有用工具,比如inspect模块:
import inspect
class MyClass:
    def my_method(self):
        return "Hello, world!"
print(inspect.getmembers(MyClass))  
getmembers函数返回一个包含所有成员的列表。五、总结
Python的反射和内省机制提供了强大的工具,使得我们的代码可以在运行时查看和修改自身。










