天天看點

55 - hasattr()、getattr()、setattr()的作用

請用代碼說明hasattr、getattr和setattr的作用

'''
hasattr: 可以判斷一個對象是否包含某個屬性
getattr: 可以擷取對象中某一個屬性的值
setattr: 可以設定對象中某一個屬性的值
'''

class Person():
    def __init__(self):
        self.name = 'ruochen'
        self.age = 18
    def show(self):
        print(self.name)
        print(self.age)
        
if hasattr(Person, 'show'):
    print('存在show方法')
    
person = Person()
setattr(person, 'sex', '男')
setattr(person, 'age', 21)
print(getattr(person, 'sex'))
print(getattr(person, 'age'))
print(getattr(person, 'name'))

person.show()      
存在show方法
男
21
ruochen
ruochen
21