Day33.反射机制

1.反射机制_什么是反射机制和为什么要用反射

2.反射机制_实现反射机制的步骤

# todo 3. 如何实现反射?
class People:
    def __init__(self, name, age):
        self.name=name
        self.age=age
    
    def say(self):
        print('<{}:{}>'.format(self.name, self.age))

obj = People('people1', 18)


# todo 实现反射机制的步骤
# todo 1. 先通过dir:查看某一个对象下,可以`.`出哪些属性来
print('1.先通过dir:查看某一个对象下,可以`.`出哪些属性来'.center(40, '-'))
print(dir(obj), '\n')


# todo 2. 可以通过字符串反射到真正的属性上,得到属性
print('2.可以通过字符串反射到真正的属性上,得到属性'.center(40, '-'))
print(obj.__dict__[dir(obj)[-2]], '\n')


# todo 3. 和上方原理相同的四个内置函数的使用: 通过字符串来操作属性值
print('和上方原理相同的四个内置函数的使用'.center(40, '-'))
# 1. hasattr()
print('hasattr判断是否有该属性'.center(30, '-'))
print(hasattr(obj, 'name'))
print(hasattr(obj, 'say'))
print(hasattr(obj, 'x'), '\n')
# 2. getattr()
print('getattr等同于obj.name'.center(30, '-')) 
print(getattr(obj, 'name'), '\n')
# 3. setattr() 
print('setattr修改数值,修改完再次获取对象内容'.center(30,'-'))    
setattr(obj, 'name', 'EGON')    # 改成obj.name='EGON'
print(obj.name, '\n')
# 4. delattr() 
print('delattr同于del obj.name,删掉对象的属性'.center(40, '-'))
print('delattr执行前:', obj.__dict__)
delattr(obj, 'name')
print('delattr执行后:', obj.__dict__, '\n')

3.反射机制_使用反射方法调用对象的方法和类下面的函数

# todo 3. 如何实现反射?
class People:
    def __init__(self, name, age):
        self.name=name
        self.age=age
    
    def say(self):
        print('<{}:{}>'.format(self.name, self.age))

obj = People('people1', 18)


res1 = getattr(obj, 'say')      # 对象.方法:obj.say
res2 = getattr(People, 'say')   # 类.函数:People.say
print('对象.方法:obj.say:', res1)
print('类.函数:People.say:', res2, '\n')

posted on 2024-07-11 17:12  与太阳肩并肩  阅读(0)  评论(0编辑  收藏  举报

导航