反射
- hasattr(obj,name_str):判读一个对象里是否有指定对应的字符串的方法
- getattr(obj,name_str):获取对象中字符串方法的字符串地址
- setattr(obj,'y',v):setattr(x, 'y', v) is equivalent to ``x.y = v''
# Author:Li Dongfei
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating %s." %(self.name,food))
d = Dog("旺财")
choice = input(">>>: ".strip())
print(hasattr(d,choice)) #判断d有没有$choice的属性
#print(getattr(d,choice)) #获取内存对象地址
#getattr(d,choice)() #加()来调用执行
if hasattr(d,choice):
func = getattr(d,choice)
func("baozi")
# Author:Li Dongfei
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating %s." %(self.name,food))
d = Dog("旺财")
choice = input(">>>: ".strip())
print(hasattr(d,choice)) #判断d有没有$choice的属性
#print(getattr(d,choice)) #获取内存对象地址
#getattr(d,choice)() #加()来调用执行
if hasattr(d,choice):
delattr(d,choice)
print(d.name)
# Author:Li Dongfei
def bulk(self):
print("%s is wangwang" %self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating %s." %(self.name,food))
d = Dog("旺财")
choice = input(">>>: ".strip())
print(hasattr(d,choice)) #判断d有没有$choice的属性
#print(getattr(d,choice)) #获取内存对象地址
#getattr(d,choice)() #加()来调用执行
if hasattr(d,choice):
func = getattr(d,choice)
else:
setattr(d,choice,bulk)
d.talk(d)
# Author:Li Dongfei
def bulk(self):
print("%s is wangwang" %self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating %s." %(self.name,food))
d = Dog("旺财")
choice = input(">>>: ".strip())
if hasattr(d,choice):
getattr(d,choice)
else:
setattr(d,choice,None)
v = getattr(d,choice)
print(v)
# Author:Li Dongfei
def bulk(self):
print("%s is wangwang" %self.name)
class Dog(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("%s is eating %s." %(self.name,food))
d = Dog("旺财")
choice = input(">>>: ".strip())
if hasattr(d,choice):
getattr(d,choice)
else:
setattr(d,choice,bulk)
func = getattr(d,choice)
func(d)