可以使用 hasattr() 函数来判断一个对象是否有某个属性。

示例代码如下:

class MyClass:
    def __init__(self):
        self.my_attr = 'Hello'

    def check_attr(self):
        if hasattr(self, 'my_attr'):
            print('my_attr exists')
        else:
            print('my_attr does not exist')


obj = MyClass()
obj.check_attr()

输出结果为:

my_attr exists

如果将 self.my_attr = 'Hello' 改为 del self.my_attr,则输出结果为:

my_attr does not exist
Python 判断对象属性是否存在:使用 hasattr() 函数

原文地址: http://www.cveoy.top/t/topic/fR4Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录