python 实例对象时后在一个方法内判断某个类属性不存在
可以使用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
原文地址: https://www.cveoy.top/t/topic/iUxT 著作权归作者所有。请勿转载和采集!