Python 反射

 

反射
hasattr(obj,name_str),判断一个对象里是否有对应的字符串的方法
getattr(obj,name_str),得到对象里对应字符串的方法,并执行

 1 class Dog(object):
 2     def __init__(self, name):
 3         self.name = name
 4 
 5     def eat(self, food):
 6         print('%s is eating ... %s' % (self.name, food))
 7         
 8 def bluk(self):
 9     print('%s is yell....' % self.name)
10 
11 
12 d = Dog('dog1')
13 
14 choice = input('>>:')
15 if hasattr(d, choice):
16 
17     # 删除属性
18     delattr(d, choice)
19     print(d.name)
20 
21     # 当输入name时,将name复制为dog
22     # attr = getattr(d, choice)
23     # setattr(d, choice, 'dog2')
24     # print(d.name)
25 
26     # 当输入eat时的代码
27     # getattr(d, choice)('meat')
28 
29 else:
30 
31     # 无方法,给属性直接赋值
32     setattr(d, choice, 22)
33     print(getattr(d, choice))
34 
35     # setattr(d,choice,None)
36     # print(getattr(d,choice))
37 
38     # setattr(d, choice, bluk)
39     # d.talk(d)
View Code

 

转载于:https://www.cnblogs.com/Linc2010/p/9011621.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值