反射

作者: 魔曦帝天 | 来源:发表于2019-09-25 20:20 被阅读0次
    class Person:
        city='beijing'
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def intro(self):
            return f"{self.name}" 
    shark=Person("alibrother",12)
    print(hasattr(Person,'city'))    判断 类的实例 shark 是否有某些属性,
    print(hasattr(shark,'city'))       有则True ,否则false
    

    getattr()获取对象属性

    print(getattr(Person,'city'))
    print(getattr(shark,'city'))
    print(getattr(shark,'intro'))
    f=getattr(shark,'name')
    print(f)
    

    setattr() 设置对象属性的值

    setattr(shark,'name','leqian')  #修改对象的属性
    setattr(shark,'age',20)
    print(getattr(shark,'name')) 
    print(getattr(shark,'age')) 
    
    

    delattr() 删除属性

    delattr(shark,'name')
    setattr(shark,'name','alibrother')
    print(getattr(shark,'name','no'))  #默认没有值,会返回no
    

    相关文章

      网友评论

          本文标题:反射

          本文链接:https://www.haomeiwen.com/subject/apflyctx.html