python 判断某个类属性不存在
可以使用hasattr()函数来判断某个类属性是否存在。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
原文地址: http://www.cveoy.top/t/topic/iUxx 著作权归作者所有。请勿转载和采集!