反射
1.反射的作用:把字符串反射成内存中的对象的地址。两句话搞定所有判断
#格式:
if hasattr(d,choice):
getattr(d,choice)
else:
setattr(d,choice,bulk) #d.talk=bulk
func=getattr(d,choice)
func(d)
hasattr(obj,name_str):判断一个对象obj里是否有对应的name_str字符串的方法。
getattr(obj,name_str) : 根据字符串去获取obj对象里的对应的方法的内存地址。
setattr(obj,'y',z), is equivalent to x.y=z
delattr(obj,name): 删除obj.name
class Dog(object):
def __init__(self,name):
self.name=name
def eat(self):
print("%s is eating"%self.name)
d=Dog("benben")
choice=input(">>:").strip()
print(hasattr(d,choice))
print(getattr(d,choice)) #找到内存地址
getattr(d,choice)()
运行结果:
>>:eat True <bound method Dog.eat of <__main__.Dog object at 0x0000000001312BE0>> benben is eating
2.调用方式
class Dog(object):
def __init__(self,name):
self.name=name
def eat(self,food):
print("%s is eating %s...."%(self.name,food))
d=Dog("benben")
choice=input(">>:").strip()
if hasattr(d,choice):
func=getattr(d,choice)
func("meat")
运行结果:
>>:eat benben is eating meat....
3.setattr 动态增加一个方法。方法需要加括号才能调用。
class Dog(object):
def __init__(self,name):
self.name=name
def eat(self,food):
print("%s is eating %s...."%(self.name,food))
d=Dog("benben")
choice=input(">>:").strip()
if hasattr(d,choice):
func=getattr(d,choice)
func("meat")
else:
setattr(d,choice,bulk) #d.choice=bulk
d.talk(d)
运行结果:
>>:talk benben is yelling...
4.setattr 动态增加一个属性。属性不需要加括号就可以调用了。
class Dog(object):
def __init__(self,name):
self.name=name
d=Dog("benben")
choice=input(">>:").strip()
if hasattr(d,choice):
func=getattr(d,choice)
func("meat")
else:
setattr(d,choice,22) #d.choice=22,choice=age
print(getattr(d,choice))
运行结果:
>>:age 22
5.如果客户端输入的是一个已经存在的属性:
class Dog(object):
def __init__(self,name):
self.name=name
d=Dog("benben")
choice=input(">>:").strip()
if hasattr(d,choice):
attr=getattr(d,choice) #attr是一个字符串,当修改字符串属性时,在此处没用
setattr(d,choice,"Jack")
else:
setattr(d,choice,22) #d.choice=22,choice=age
print(getattr(d,choice))
print(d.name)
运行结果:
>>:name Jack
6. delattr()
class Dog(object):
def __init__(self,name):
self.name=name
d=Dog("benben")
choice=input(">>:").strip()
if hasattr(d,choice):
delattr(d,choice)
else:
setattr(d,choice,22) #d.choice=22,choice=age
print(getattr(d,choice))
print(d.name)
运行结果:
>>:name Traceback (most recent call last): File "<encoding error>", line 12, in <module> AttributeError: 'Dog' object has no attribute 'name'
浙公网安备 33010602011771号