反射是指通过字符串映射或修改程序运行时的状态、属性、方法, 有以下4个方法
    1.getattr(object, name, default = None)
        根据字符串获取 obj 对象里对应 str 方法的内存地址
示例:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print('%s is eating %s' % (self.name, food))


dog1 = Dog('Dog1')
choice = input('>>').strip()
if hasattr(dog1, choice):
    getattr(dog1, choice)('bone')   # 根据字符串获取对象里对应方法的内存地址,传入‘bone’执行
    print(getattr(dog1, choice))    # 打印属性
    
    
    输出结果:

# eat
# Dog1 is eating bone
# <bound method Dog.eat of <__main__.Dog object at 0x00000249C4C3B780>>

    2.hasattr(object, name)
        判断一个 obj 对象里是否有对应 str 字符串
示例:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print('%s is eating %s' % (self.name, food))


dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice))        # 判断一个 obj 对象里是否有对应 str 字符串


输出结果:

# eat
# True

    3.setattr(object, y, v)
        给类新加了一个属性等于: obj.y = v
传入属性示例:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print('%s is eating %s' % (self.name, food))


dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice))        # 判断一个 obj 对象里是否有对应 str 字符串
if hasattr(dog1, choice):
    print(getattr(dog1, choice))    # 打印修改前的属性
    setattr(dog1, choice, 'Dog2')   # 如果属性存在,可以通过 setattr 进行修改
    print(getattr(dog1, choice))    # 打印修改后的属性
else:
    setattr(dog1, choice, None)     # 给类新加了一个属性 == dog1.choice = None
    print(getattr(dog1, choice))    # 打印新加入的属性
  


修改已有属性输出结果:

#>> name
# True
# Dog1
# Dog2
#  增加新的属性输出结果:
# >>age
# False
# None

 

传入方法示例:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print('%s is eating %s' % (self.name, food))


def bulk(self):                     # 传入方法需要提前写好
    print('%s: woof,woof!' % self.name)


dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice))        # 判断一个 obj 对象里是否有对应 str 字符串
if hasattr(dog1, choice):
    pass
else:
    setattr(dog1, choice, bulk)     # 给类新加了一个方法
    dog1.bulk(dog1)                 # 调用新加入的方法 bulk
  

输出结果:
# >>bulk
# False
# Dog1: woof,woof!

4.delattr(object, name)
        删除 obj 对象中对应属性
示例:

class Dog(object):
    def __init__(self, name):
        self.name = name

    def eat(self, food):
        print('%s is eating %s' % (self.name, food))


dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice))        # 输出 True
if hasattr(dog1, choice):
    delattr(dog1, choice)
    print(getattr(dog1, choice))    # 打印会报错
posted on 2019-11-21 16:58  Mr丶zhao  阅读(101)  评论(0编辑  收藏  举报