Python中hasattr()、getattr()、setattr()函数的区别以及使用

1. hasattr(object, name)

  • 特点:判断一个实例对象是否有name属性或者方法,或者判断一个类是否有name类属性和方法返回值为Ture或False类型
def foo(object):
	class_name = "class_name"
	
	def __init__(self):
		self.name = "name"
	
print(hasattr(foo, "class_name"))  # True

test1 = foo()
print(hasattr(test1, "name"))  # True
print(hasattr(test1, "class_name"))  # False
# 实例对象,无法获取类方法

2. getattr(object, name[,default])

  • 特点:获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印默认值,如果没有默认值,会报错
def foo(object):
	def __init__(self):
		self.name = "name:
	

test1 = foo()
print(getattr(test1, "name"))
print("*"*30)
print(getattr(test1, "class_name"))
print("*"*30)
print(getattr(test1, "class_name", "this is the default"))

name
-******************************
“foo” object has no attribute “class_name”
-******************************
‘this is the default’

3. setattr(object, name, values)

  • 特点:给对象的属性赋值,如果属性不存在,先创建再赋值
class foo(object):
	def __init__(self):
		self.name = "name"


test1 = foo()
print(getattr(test1, "name", "there has not this"))
print("*"*30)
setattr(teset1, "name", "laoli")
print(getattr(test1, "name", "there has not this"))
print("*"*30)
setattr(test1, "age", 20)
print(getattr(test1, "age", "there has not this"))

py
name
.******************************
laoli
.******************************
20

猜你喜欢

转载自blog.csdn.net/weixin_40576010/article/details/88390486
今日推荐