classMyClass:defexisting_method(self):print("Existing method")def_protected_method(self):print("Protected method")def__private_method(self):print("Private method")
my_instance = MyClass()# 检测实例是否具有指定的方法并调用它 ifhasattr(my_instance,'existing_method'):
method =getattr(my_instance,'existing_method')
method()else:print("Method does not exist")# 检测实例是否具有指定的方法并调用它 ifhasattr(my_instance,'non_existing_method'):
method =getattr(my_instance,'non_existing_method')
method()else:print("Method does not exist")# 检测实例是否具有保护方法并尝试调用它 ifhasattr(my_instance,'_protected_method'):
method =getattr(my_instance,'_protected_method')
method()else:print("Protected method does not exist")# 检测实例是否具有私有方法并尝试调用它 ifhasattr(my_instance,'__private_method'):
method =getattr(my_instance,'__private_method')
method()else:print("No class name prefix Private method does not exist")ifhasattr(my_instance,'_MyClass__private_method'):
method =getattr(my_instance,'_MyClass__private_method')
method()else:print("Private method does not exist")
Existing method
Method does not exist
Protected method
No class name prefix Private method does not exist
Private method