python中的简单反射

class People:
   def __init__(self,name,age,gender):
        self.name=name
        self.age=age
        self.gender=gender

obj=People('egon',18,'male')
print(dir(obj))# 列表中查看到的属性全为字符串
print(obj.__dict__)# 查看对象命名空间的数据

print(dir(People))# 列表中查看到的属性全为字符串
print(obj.__class__.__dict__)
print(People.__dict__)# 列表中查看到的属性全为字符串





class Teacher:
    def __init__(self,full_name):
        self.full_name =full_name

t=Teacher('Egon Lin')

# hasattr(object,'name')
print(hasattr(t,'full_name')) # 按字符串'full_name'判断有无属性t.full_name

# getattr(object, 'name', default=None)
print(getattr(t,'full_name',None)) # 等同于t.full_name,不存在该属性则返回默认值None

# setattr(x, 'y', v)
print(setattr(t,'age',18))# 等同于t.age=18
print(t.age)
# delattr(x, 'y')
print(delattr(t,'age')) # 等同于del t.age
posted @ 2020-06-05 09:15  梦乡尘子  阅读(121)  评论(0编辑  收藏  举报