Python判断类属性是否存在 - hasattr()方法详解

在Python中,我们经常需要检查一个类是否具有特定的属性。这时,hasattr() 函数就派上用场了。

hasattr() 函数

hasattr() 函数接受两个参数:

  1. object: 要检查的对象,可以是类、实例对象等。
  2. name: 要查找的属性名,以字符串形式传递。

如果对象中存在指定的属性,则 hasattr() 函数返回 True,否则返回 False

代码示例

class MyClass:
    def __init__(self):
        self.foo = 1

my_obj = MyClass()

if hasattr(my_obj, 'foo'):
    print('foo exists')
else:
    print('foo does not exist')

if hasattr(my_obj, 'bar'):
    print('bar exists')
else:
    print('bar does not exist')

输出结果:

foo exists
bar does not exist

总结

hasattr() 函数提供了一种简单而有效的方式来检查 Python 对象中是否存在特定属性。这在编写动态代码和处理可能具有不同属性的对象时特别有用。

Python判断类属性是否存在 - hasattr()方法详解

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

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