Python学习之反射

#!/usr/bin/env python
#-*-coding:utf8-*-

def bulk(self):
    print("%s is jiao ...."%self.name)

class Dog(object):
    def __init__(self,name):
        self.name=name


    def eat(self,food):
        print("%s is eating ...."%self.name,food)

d= Dog("dfxa")
choice = input(">>:").strip()

if hasattr(d,choice):  #判断一个d(对象)里是否有对应的choice字符串方法
    # delattr(d,choice)  # Deletes the named attribute from the given object.
    # delattr(x, ‘y‘) is equivalent to ``del x.y‘‘
    # 相当于 del d.choice
     func = getattr(d,choice) #根据字符串去获取d对象里的对应方法的内存地址
     func("cheng")
    # attr = getattr(d,choice)
    # setattr(d,choice,"drr")

else:
    # 将给定对象的命名属性设置为指定值
    setattr(d,choice,22)  # choice是字符串,相当于 d.choice = z
    print(getattr(d,choice))
print(d.name)
  setattr(d,choice,bulk)
  d.tlk(d)  #动态的把类外面的方法装配到类里,通过字符串的形式,调用需要把自己传进去   输入 tlk才能调用>>:tlkdfxa is jiao ....

相关推荐