首页 > 其他 > 详细

反射、getattr

时间:2018-03-17 10:37:36      阅读:179      评论:0      收藏:0      [点我收藏+]
#coding=utf-8
class Dog(object):

    def __init__(self,name):
        self.name = name

    def eat(self):
        print ‘1234‘

def talk(self):
    print ‘678678‘
d = Dog(‘xiaobai‘)
#choice = raw_input(‘input:‘).strip()
#print (hasattr(d,choice))   #判断一个对象里是否有对应的字符串的方法映射
#getattr(d,choice)()          #根据字符串去获取对象里的对应的方法的内存地址
#setattr(d,choice,talk)        #给指定对象加一个方法  d.choice=talk
#d.talk(d)

#setattr(d,choice,22)             #给指定对象加一个实例变量
#print (getattr(d,choice))
#i = getattr(d,‘eat‘)
# print (hasattr(d,‘name‘))
# delattr(d,‘name‘)              #删除类变量
# d.name
i = ‘eat1‘
if hasattr(d,i):
    getattr(d,i)()
else :
    setattr(d,i,talk)
    func = getattr(d,i)
    func(d)

 

反射、getattr

原文:https://www.cnblogs.com/qiangayz/p/8587025.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!