python 反射

1、getattr
class F:
def __init__(self, name):
self.name = name

def show(self):
return self.name
obj = F('tom')
s = getattr(obj, 'name')
r = getattr(obj, 'show')
print(s) # tom
print(r())# tom

getattr反射类F中的属性,getattr(对象,类属性)

2、hasattr
class F:
def __init__(self, name):
self.name = name

def show(self):
return self.name
obj = F('tom')
s = hasattr(obj, 'name')
h = hasattr(obj, 'age')
print(s) # Ture
print(h) # False

hasattr判断类中存在的属性,如果存在返回Ture,如果不存在返回False

3、setattr
class F:
def __init__(self, name):
self.name = name

obj = F('tom')
print(obj.name) # tom
# 对已存在的属性值赋值
setattr(obj, 'name', 'jack')
print(obj.name) # jack
# 设置新的属性值
setattr(obj, 'age', 12)
print(obj.age) # 12
setattr 用于设置属性值,该属性不一定是存在的

4、delattr

class F:
    def __init__(self, name):
self.name = name

obj = F('tom')
print(obj.name) # tom
delattr(obj, 'name')
obj.name
当执行delattr 后,在调用name属性,会提示“AttributeError: 'F' object has no attribute 'name'”

delattr 用于删除属性值
posted @ 2019-12-18 09:23  菜菜_包包  阅读(308)  评论(0编辑  收藏  举报