python 检测类中有没有给定的属性 `hasattr(object, attribute)`

本文介绍了如何在Python中使用`hasattr`和`getattr`函数检测类实例是否存在公开方法(如`existing_method`)、保护方法(如`_protected_method`)以及私有方法(需通过类名前缀)。实例展示了如何正确调用这些方法或处理不存在的情况。
摘要由CSDN通过智能技术生成

TL;DR

  • 既可以检测方法,也可以检测属性
    方法也算是一种属性。
  • 可以检测一般,保护,私有成员
    注意 私有成员 在解释时会加上被隐式加上类名,以起到保护作用。

验证一下

class MyClass:  
    def existing_method(self):  
        print("Existing method")  
  
    def _protected_method(self):  
        print("Protected method")  
  
    def __private_method(self):  
        print("Private method")  
  
  
my_instance = MyClass()  
  
# 检测实例是否具有指定的方法并调用它  
if hasattr(my_instance, 'existing_method'):  
    method = getattr(my_instance, 'existing_method')  
    method()   
else:  
    print("Method does not exist")  
  
# 检测实例是否具有指定的方法并调用它  
if hasattr(my_instance, 'non_existing_method'):  
    method = getattr(my_instance, 'non_existing_method')  
    method()
else:  
    print("Method does not exist")  
  
# 检测实例是否具有保护方法并尝试调用它  
if hasattr(my_instance, '_protected_method'):  
    method = getattr(my_instance, '_protected_method')  
    method() 
else:  
    print("Protected method does not exist")  
  
# 检测实例是否具有私有方法并尝试调用它  
if hasattr(my_instance, '__private_method'):  
    method = getattr(my_instance, '__private_method')  
    method() 
else:  
    print("No class name prefix Private method does not exist")  
  
if hasattr(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
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值