Python中一切皆对象,在Python中的反射:通过字符串的形式操作对象的属性
class Person: role = ‘person‘ def __init__(self,name): self.name = name def walk(self): print("%s is walking"%self.name) wangys = Person(‘wangys‘) print(hasattr(wangys,‘role‘)) print(hasattr(wangys,‘name‘)) print(hasattr(wangys,‘walk‘)) print(hasattr(wangys,‘eat‘)) True True True False print(getattr(wangys,‘role‘)) print(getattr(wangys,‘name‘)) print(getattr(wangys,‘walk‘)) getattr(wangys,‘walk‘)() person wangys <bound method Person.walk of <__main__.Person object at 0x00000216037DDA90>> wangys is walking
通常hasattr跟getattr结合使用
class Person: role = ‘person‘ def __init__(self,name): self.name = name def walk(self): print("%s is walking"%self.name) wangys = Person(‘wangys‘) if hasattr(wangys,‘role‘): print(getattr(wangys,‘role‘)) if hasattr(wangys,‘walk‘): getattr(wangys,‘walk‘)() if hasattr(wangys,‘eat‘): getattr(wangys,‘eat‘)() else: print(‘没有改方法‘) person wangys is walking 没有改方法
原文:https://www.cnblogs.com/wc89/p/10391909.html