Python3 —— 反射

反射
   hasattr(obj, name_str) 判断一个对象obj里是否有对应的name_str字符串方法的方法
   getattr(obj, name_str) 根据字符串获取obj对象里的对应方法的内存地址
   setattr(obj, name_str) 添加新属性
   delattr(obj, name_str) 删除属性
def job(self):
    print("%s is working" % self.name)
class Person(object):
    def __init__(self, name):
        self.name = name
    def eat(self, food):
        print("%s is eating %s." % (self.name,food))

d = Person('liming')
choice = input(">>:").strip()


if hasattr(d,choice):
    func = getattr(d, choice) # 输入 eat
    func("apple") # 调用 eat 方法
else:
    setattr(d,choice,job) # 添加反射方法 输入work
    d.work(d)

>>:eat
liming is eating apple.

>>:work
liming is working

def job(self):
    print("%s is working" % self.name)
class Person(object):
    def __init__(self, name):
        self.name = name
    def eat(self, food):
        print("%s is eating %s." % (self.name,food))

d = Person('liming')
choice = input(">>:").strip()

if hasattr(d,choice):
    attr = getattr(d,choice) # 输入name
    setattr(d,choice,"hanmeimei") # 修改属性
    print(getattr(d, choice)) # 打印修改的属性
else:
    setattr(d,choice,22) # 添加反射属性 输入 age
    print(getattr(d,choice))

>>:name
hanmeimei

>>:age
22

def job(self):
    print("%s is working" % self.name)
class Person(object):
    def __init__(self, name):
        self.name = name
    def eat(self, food):
        print("%s is eating %s." % (self.name,food))

d = Person('liming')
choice = input(">>:").strip()

if hasattr(d,choice):
    delattr(d,choice) # 删除属性
    print(getattr(d, choice)) # 打印删除的属性

>>:name
Traceback (most recent call last):
  File "D:/PyCharm/PycharmProjects/s12/day07/反射.py", line 21, in <module>
    print(getattr(d, choice)) # 打印删除的属性
AttributeError: 'Person' object has no attribute 'name'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值