This article introduces the code implementation of Python radiation, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it
''' 放射 hasattr(obj, name_str):判断一个对象obj里是否有对应的name_str字符串的方法 getattr(obj, name_str):根据name_str字符串去获取obj对象里的对应的方法的内存地址 ''' def bulk(self): print("%s is yelling..." % self.name) class People(object): def __init__(self, name): self.name = name def talk(self): print("%s is talking..." % self.name) User = People("UserPython") choice = input(">>>:") # 判断一个对象User里是否有对应的choic = talk字符串的方法 # print(hasattr(User, choice)) #True # 根据choice字符串去获取User对象里的对应的方法的内存地址 # print(getattr(User, choice)) #<bound method People.talk of <__main__.People object at 0x0000000002741208>> if hasattr(User, choice): func = getattr(User, choice) func() else: setattr(User, choice, bulk) User.bulk(User)
Related recommendations:
Python--Reflection/Introspection
The above is the detailed content of Code implementation of Python radiation. For more information, please follow other related articles on the PHP Chinese website!