反射
介绍
反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。这一概念的提出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象方面取得了成绩。
python面向对象中的反射**:通过字符串的形式操作对象相关的属性。**python中的一切事物都是对象(都可以使用反射)
四个可以实现自省的函数
下列方法适用于类和对象(一切皆对象,类本身也是一个对象)
def hasattr(*args, **kwargs):
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass
def getattr(object, name, default=None):
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
def setattr(x, y, v):
"""
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass
def delattr(x, y):
"""
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''
"""
pass
例子
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age
person = Person("黑子", 20)
print("-----属性反射-----")
# 反射的增删改查
if hasattr(person, "name"):
print(getattr(person, "name")) # 获取属性
delattr(person, "name") # 删除属性
setattr(person, "name", "白子") # 新增或者修改属性
else:
print("没有name这个属性")
print(person.name)
print("-----方法反射-----")
# 方法反射
def walk(name):
print("你好呀,我们来散步吧!!!我叫", name)
# 新增
print(hasattr(person, "walk"))
setattr(person,"walk", walk)
print(hasattr(person, "walk"))
# 获取
person.walk("武大")
walk_p = getattr(person, "walk")
walk_p("武二")
# 删除
delattr(person, "walk")
print(hasattr(person, "walk"))
输出
-----属性反射-----
黑子
白子
-----方法反射-----
False
True
你好呀,我们来散步吧!!!我叫 武大
你好呀,我们来散步吧!!!我叫 武二
False
跨模块反射
在做跨模块导入的时候,先看一个双下划线方法
print(__name__)
# __name__获取模块名
if __name__ == "__main__":
print("当前模块输出")
当前模块输出
__main__
当前模块输出
其他模块导入
import test_name
输出
test_name
__name__可以输出当前模块的名称
当前模块反射
mod = sys.modules[__name__]
if hasattr(mod, "person"):
print(getattr(mod, "person").name)
getattr(mod, "person").walk("武大")
跨模块导入反射:
-
被导入的模块
class Person: def __init__(self, name, age): self.name = name self.__age = age def walk(self, name): print("你好呀,我们来散步吧!!!我叫", name) person = Person("小黑", 20) print(__name__) # __name__获取模块名 if __name__ == "__main__": print("当前模块输出")
-
导入模块
import test_name import sys mod = sys.modules["test_name"] if hasattr(mod, "person"): print(getattr(mod, "person").name) getattr(mod, "person").walk("武大")
输出
test_name 小黑 你好呀,我们来散步吧!!!我叫 武大