CSIC_716_20191128【面向对象高级----反射】

反射

反射是通过'字符串'对 对象的属性进行操作,反射有四个内置的方法。

hasattr  通过字符串 判断对象的属性或者方法是否存在

getattr  通过字符串  获取对象的属性或者方法               getattr (  ref  'z'   '没有值')  可以设置返回值,防止报错

setattr  通过字符串   设置对象的属性或者方法

delattr  通过字符串  删除对象的属性或者方法

# _*_ coding: gbk _*_
# @Author: Wonder

class Reflection:
    def __init__(self, x, y):
        self.m = x
        self.n = y


ref = Reflection(1, 2)
print(hasattr(ref, 'm'))  # True

print(getattr(ref, 'n'))  # 2

print(getattr(ref, 'z'))  # AttributeError: 'Reflection' object has no attribute 'z'
print(getattr(ref, 'z', '没有值'))  # 没有值

setattr(ref, 'a', [1, 2, 3])  
print(getattr(ref, 'a'))  # [1, 2, 3]

delattr(ref, 'n')
print(getattr(ref, 'n', '么得'))  # 么得

  

猜你喜欢

转载自www.cnblogs.com/csic716/p/11951428.html