反射

一共就4个函数
attr: attribute

getattr()
从xxx对象中获取到xxx属性值
hasattr()
判断xxx对象中是否有xxx属性值
delattr()
从xxx对象中删除xxx属性
setattr()
设置xxx对象中的xxx属性为xxxx值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# import master   # 报错不用管
#
# # print("""
# #     1. chi:  大牛特别能吃
# #     2. he: 大牛特别能喝
# #     3. shui: 大牛特别能睡
# #     4. play: 大牛特别能玩儿
# #     5. sa: 大牛很喜欢撒谎
# # """)
# # while 1:
# #     content = input("请输入你要执行的函数:")
# #     if content == "1":
# #         master.chi()
# #     elif content == "2":
# #         master.he()
# #     elif content =="3":
# #         master.shui()
# #     elif content == "4":
# #         master.play_1()
# #     elif content == "5":
# #         master.sa()
#
# while 1:
#     content = input("请输入你要测试的功能:") # 用户输入的功能是一个字符串
#
#     # 判断 xxx对象中是否包含了xxxxx
#     if hasattr(master, content):
#         xx = getattr(master, content)
#         xx()
#         print("有这个功能")
#     else:
#         print('没有这个功能')
 
 
 
 
# 对于模块而言可以使用getattr, hasattr, 同样对于我们的对象也可以执行类似的操作
 
class Person:
    def __init__(self, name, laopo):
        self.name = name
        self.laopo = laopo
 
 
= Person("宝宝""林志玲")
 
print(hasattr(p, "laopo")) #
print(getattr(p, "laopo")) # p.laopo
 
# setattr(p, "laopo", "胡一菲") # p.laopo = 胡一菲
# setattr(p, "money", 100000000000) # p.money = 100000000
#
# print(p.laopo)
# print(p.money)
#
# delattr(p, "laopo") # 把对象中的xxx属性移除.  != p.laopo = None
# print(p.laopo)
原文地址:https://www.cnblogs.com/heheda123456/p/10204807.html