Python反射练习
作者:互联网
'''
#hasattr()判断真假布尔值True Faster
#delattr()删除
#setattr()新增
#getattr()#查看
class Person(object):
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
huchangxi = Person("huchangxi", 22, "男")
def check_attr():
attr = input("呼长喜的属性 >>>")
# print(attr, type(attr))
is_exist = hasattr(huchangxi, attr) # 布尔值
if is_exist:
print(getattr(huchangxi, attr))
else:
print("呼长喜不存在属性", attr)
choice = input("是否设置该属性?Y/N:")
if choice.upper() == "Y":
value = input(f"请输入属性{attr}的值:")
print(value)
setattr(huchangxi, attr, value)
print("赋值成功")
while 1:
print("""
1. 查看属性
2. 删除属性
3. 修改属性
4. 添加属性
""")
choice = input("请输入选择的序号>>>")
if choice == "1":
check_attr()
elif choice == "2":
chongxin = ""
while 1:
del_attr = input(f"请{chongxin}输入删除属性:")
if hasattr(huchangxi, del_attr):
delattr(huchangxi, del_attr)
print("删除成功!")
break
else:
chongxin = "重新"
print("不存在该属性", del_attr)
'''
标签:反射,huchangxi,attr,Python,练习,choice,print,input,属性 来源: https://www.cnblogs.com/A121/p/16167856.html