· hasattr(obj,name_str):判断一个对象obj里是否有对应的name_str字符串的方法
· getattr(obj,name_str):根据字符串去获取obj对象里的对应的方法的内存地址
· setattr(obj,name_str,func):设置属性,相当于“obj.name_str = func”
· delattr(obj,name_str):删除属性
示例代码:
class dog(object):
    def __init__(self,name):
        self.name = name
    def eat(self,food):
        print('%s is eating...' % self.name,food)

def walk(self):
    print('%s is walking...' % self.name)

d = dog('erha')
choice = input('function:').strip()
if hasattr(d,choice):   # 判断对象里是否有对应的属性
    print(getattr(d,choice))
    # delattr(d,choice)   # 删除属性
    func = getattr(d,choice)   # 获取属性
    func('meet')
    # setattr(d,choice,'hsq')   # 改变私有属性使用setattr
    # print(getattr(d,choice))
else:
    setattr(d,choice,walk)   # 将walk添加进类中
    func = getattr(d,choice)
    func(d)
# 输出:
function:eat
erha is eating... meet
<bound method dog.eat of <__main__.dog object at 0x00000000023DDC88>>

function:aaa
erha is walking...

 

 posted on 2017-11-08 14:26  super2feng  阅读(129)  评论(0)    收藏  举报