Python 类内判断属性是否存在:使用 hasattr() 函数
在 Python 中,可以使用 hasattr() 函数来判断某个类是否具有某个属性。hasattr() 函数接受两个参数,第一个参数是类的实例或类本身,第二个参数是要判断的属性名。如果属性存在,则返回 True,否则返回 False。
下面是一个示例代码:
class MyClass:
def __init__(self):
self.attribute = 10
my_object = MyClass()
if hasattr(my_object, 'attribute'):
print('attribute exists')
else:
print('attribute does not exist')
输出结果为:
attribute exists
如果要判断类本身是否具有某个属性,可以将类本身作为 hasattr() 函数的第一个参数,例如:
class MyClass:
attribute = 10
if hasattr(MyClass, 'attribute'):
print('attribute exists')
else:
print('attribute does not exist')
输出结果为:
attribute exists
如果要判断类属性不存在,可以使用 not 运算符对 hasattr() 函数的结果取反,例如:
class MyClass:
def __init__(self):
self.attribute = 10
my_object = MyClass()
if not hasattr(my_object, 'nonexistent_attribute'):
print('nonexistent_attribute does not exist')
输出结果为:
nonexistent_attribute does not exist
原文地址: http://www.cveoy.top/t/topic/fR4V 著作权归作者所有。请勿转载和采集!