Day 5-6 反射

python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

 1 #!_*_ coding:utf-8 _*_
 2 
 3 class People:
 4     def __init__(self, name, age):
 5         self.name = name
 6         self.age = age
 7 
 8     def talk(self):
 9         print("%s is talking" % self.name)
10 
11 
12 p = People("Jack",20)
13 
14 print(hasattr(p,"name"))  # 判断对象p中有没有name属性 p.__dict__["name"]
15 print(p.__dict__["name"])
16 
17 print(getattr(p, "age", None))   # 获取对象中age的值
18 print(getattr(p, "age11", None))  # 不存在会返回None
19 
20 setattr(p,"sex", "")  #可以在修改和新增
21 print(p.sex)
22 
23 delattr(p, 'age')
24 print(p.__dict__)  # {'name': 'Jack', 'sex': '男'} age已经被删除了

反射的应用:

# #!_*_ coding:utf-8 _*_
#
# class People:
#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#
#     def talk(self):
#         print("%s is talking" % self.name)
#
#
# p = People("Jack",20)
#
# print(hasattr(p,"name"))  # 判断对象p中有没有name属性 p.__dict__["name"]
# print(p.__dict__["name"])
#
# print(getattr(p, "age", None))   # 获取对象中age的值
# print(getattr(p, "age11", None))  # 不存在会返回None
#
# setattr(p,"sex", "男")  #可以在修改和新增
# print(p.sex)
#
# delattr(p, 'age')
# print(p.__dict__)  # {'name': 'Jack', 'sex': '男'} age已经被删除了
#
#
# 反射的应用.模拟用户输入一些命令,让程序去调用这些命令.
# class Service:
#     def run(self):
#         while True:
#             # inp = input(">>>>:").strip() #正常输入一个命令,判断在类中有没有这样一个属性方法.如果有就去执行.
#             inp = input(">>>>:").strip()
#             if hasattr(self,inp):
#                 func = getattr(self,inp)
#                 func()
#             elif inp == "b":
#                 break
#             else:
#                 print("input error")
#
#
#
#     def get(self):
#         print("get.....")
#
#
#     def put(self):
#         print("put.....")
class Service:
    def run(self):
        while True:
            # inp = input(">>>>:").strip() #正常输入一个命令,判断在类中有没有这样一个属性方法.如果有就去执行.
            inp = input(">>>>:").strip()
            cmds = inp.split()  # 用户传入get b.txt 这样的命令,进行分割
            print(cmds)
            if hasattr(self,cmds[0]):
                func = getattr(self,cmds[0])
                func(cmds)
            elif inp == "b":
                break
            else:
                print("input error")


    def get(self,cmds):
        print("get.....", cmds)


    def put(self,cmds):
        print("put.....",cmds)


obj = Service()

obj.run()

猜你喜欢

转载自www.cnblogs.com/lovepy3/p/8987841.html
5-6