python 反射

 hasattr

hasattr(object, name) 检查指定对象是否包含指定的属性。

class Comsumer():
    gender = 'girls'
    def __init__(self, name):
        self.name = name

    def buy(self, commodity):
        print('%s买了%s' % (self.name, commodity))

if __name__ == '__main__':
    c = Comsumer('Alice')
    print(hasattr(c, 'gender'))  #True
    print(hasattr(c, 'name'))  #True
    print(hasattr(c, 'buy'))  #True

getattr

getattr(object, name[, default])返回指定对象中指定属性的值,还可给这个属性指定默认值。

class Comsumer():
    gender = 'girls'
    def __init__(self, name):
        self.name = name

    def buy(self, commodity):
        print('%s买了%s' % (self.name, commodity))

if __name__ == '__main__':
    c = Comsumer('Alice')
    gender = getattr(c,'gender')
    print(gender)  #girls
    name = getattr(c,'name')
    print(name)  #Alice
    buyer = getattr(c,'buy')
    buyer('apple')  #Alice买了apple

setattr

setattr(object, name, value) 将指定对象的指定属性设置为指定的值。

class Comsumer():
    gender = 'girls'
    def __init__(self, name):
        self.name = name

    def buy(self, commodity):
        print('%s买了%s' % (self.name, commodity))

if __name__ == '__main__':
    c = Comsumer('Alice')
    setattr(c, 'gender', 'boy')
    print(c.gender)  #boy
    setattr(c,'name','Eason')
    print(c.name)  #Eason

delattr

delattr(object, name) 删除指定对象的指定属性。不可以删除类属性和对象方法。

class Comsumer():
    gender = 'girls'
    def __init__(self, name):
        self.name = name

    def buy(self, commodity):
        print('%s买了%s' % (self.name, commodity))

if __name__ == '__main__':
    c = Comsumer('Alice')
    delattr(c, 'name')
    print(hasattr(c, 'name'))  #False
posted @ 2019-05-27 10:18  houyongchong  阅读(188)  评论(0编辑  收藏  举报