反射
【一】什么是反射
-
反射是一种程序访问检测和修改本身属性和状态的方式
-
在Python内也有反射机制,通过字符串映射自己的内部是否具有某种属性
-
python中的一切事物都是对象(都可以使用反射)
【二】python中的四个方法
-
获取属性
-
getattr(obj,key)
-
-
判断当前属性是否存在
-
hasattr(obj,key)
-
-
向当前对象中设置属性名和属性值
-
setattr(obj,key,value)
-
-
删除对象中的指定属性
-
delattr(obj,key)
-
【三】四种方式的具体使用方法
(1)获取属性getattr(obj,key)
-
数据属性
-
在对象中映射数据属性的时候,如果对象中存在当前属性值则直接将属性值拿出来
-
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def tell(self):
print(f'{self.name} is {self.age} years old')
@classmethod
def talk(cls):
print(cls.__name__)
@staticmethod
def swim():
print(f'I am a swimming')
people = Person(name='dream', age=18)
result = getattr(people,"name")
print(result)#dream
result = getattr(people,'age')
print(result)#18
-
函数属性
-
在对象中映射函数属性的时候,如果对象中存在当前属性名对应的数据属性,则直接获取当前函数属性的内存地址,可以直接调用当前函数
-
result = getattr(people,'tell')
print(result)#<bound method Person.tell of <__main__.Person object at 0x000001C2C4F172B0>>
-
在对象中映射属性的时候,如果对象中不存在当前属性名对应的属性,会直接报错
(2)判断当前属性是否存在hasattr(obj,key)
*-->返回布尔类型
-
数据属性
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def tell(self):
print(f'{self.name} is {self.age} years old')
@classmethod
def talk(cls):
print(cls.__name__)
@staticmethod
def swim():
print(f'I am a swimming')
people = Person(name='dream', age=18)
result = hasattr(people,"name")
print(result)#True
result = hasattr(people,'age')
print(result)#True
-
函数属性
-
在对象中映射函数属性的时候,如果对象中存在当前属性名对应的数据属性,则返回True
-
people = Person(name='dream', age=18)
result = hasattr(people,'tell')
print(result)#True
-
在对象中映射属性的时候,如果对象中不存在当前属性名对应的属性,则返回False
(3)向当前对象中设置属性值和属性名setattr(obj,key,value)
-
数据属性
-
向对象中设置属性名和属性值,如果对象中存在当前属性则直接替换,否则新增
-
people = Person(name='dream', age=18)
result = setattr(people,"gender","male")
print(result)#None
print(people.gender)#male
-
函数属性
-
在对象中映射函数属性的时候,如果对象中存在当前属性名对应的数据属性,则返回True
-
def read():
print(f"这是外部的 read ")
def onr():
print(f",,,,")
people = Person(name='dream', age=18)
#设置进去的方法叫非静态方法
result = setattr(people,"read",onr)
print(result)#None
print(hasattr(people, 'read')) # True
print(getattr(people, 'read')) # <function onr at 0x0000022CA5A6AEF0>
getattr(people,"read")()#,,,,
(4)删除对象中的指定属性delattr(obj,key)
-
数据属性
-
在对象中删除数据属性的时候,如果对象中存在当前属性值则直接删除
-
people = Person(name='dream', age=18)
print(hasattr(people,'name')) # True
result = delattr(people,'name')
print(result) # None
print(hasattr(people,'name')) # False
-
函数属性
-
在对象中删除函数属性的时候,要根据参数是对象还是类来做区分
-
# print(hasattr(Person, 'tell')) # True
# 如果参数是当前对象,则无法删除函数属性
# result = delattr(people, 'tell')
# result = delattr(people, 'talk')
# result = delattr(people, 'swim')
# 如果参数是当前类,则可以删除函数属性
# result = delattr(Person, 'tell') #
# result = delattr(Person, 'talk')
# result = delattr(Person, 'swim')
# print(result) # None
# print(hasattr(Person, 'swim'))
-
在对象中删除属性的时候,如果对象中不存在当前属性名对应的属性,则直接报错