1. 旧知识回顾-反射
hasattr(object, name)
说明:判断对象object是否包含名为name的属性(方法)
测试代码如下:
class tt(object): def __init__(self): pass def AA(self): self.name=‘Lucy‘ def tes(self): while True: cmd=input(">>:").strip() if hasattr(self,cmd): #用来判断对象object的属性(name表示)是否存在。 print(‘Yes,we have fun %s‘%cmd) else: print("nonono...,we don‘t have this fun") obj=tt() obj.tes()
运行结果:
>>:AA Yes,we have fun AA >>:test nonono...,we don‘t have this fun >>:b nonono...,we don‘t have this fun >>:
时间: 2024-10-25 11:56:51