dict.items()、hasattr及setattr的用法

   class Persoon:
    age = ""
    name = ""
    city = ""


def set_attrs(attrs_dict):
# 遍历一个字典的k,v返回到一个元素
    for key, value in attrs_dict.items():
        print(key, value)
        # 如果一个对象内有相应的k,就把它的k的值设为v
        if hasattr(Persoon, key):
            setattr(Persoon, key, value)


xiaoming = {
'name':'fsafds','age':23,'city':'tianjin'
}
set_attrs(
    {'name':'fsafds','age':18,'city':'beijing'}
)

你可能感兴趣的:(dict.items()、hasattr及setattr的用法)