Python 反射(reflection)

反射是指通过字符串映射或修改程序运行时的状态、属性、方法, 有以下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))    # 打印会报错

转载于:https://www.cnblogs.com/dbf-/p/10655682.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值