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)
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字符串方法
     func = getattr(d,choice) #根据字符串去获取d对象里的对应方法的内存地址
     func("cheng")
    #不能直接print(d.choice) ,choice是一个字符串,应该按照下面的方法写
    # attr = getattr(d,choice)
    # print(attr)

else:

     setattr(d,choice,bulk)
     # 运行程序,输入talk相当于 d.talk = bulk,把bulk的内存地址赋给了talk
     # 此时函数就是talk,talk() == 调用bulk()
     #d.talk(d)  #所以这里只能调用talk()
     #动态的把类外面的方法装配到类里,通过字符串的形式,但调用需要把自己(对象)传进去
     #这样的话就把函数写死了,另一种写法
     func2 = getattr(d,choice)
     func2(d)  #这样不管输入的是talk还是bulk都可以
>>:talk

dfxa is jiao ....
 

猜你喜欢

转载自www.cnblogs.com/wengshaohang/p/12335636.html
今日推荐