python 反射机制

2021-06-30 05:03

阅读:636

标签:nbsp   method   and   bsp   style   .sh   show   def   int   

 反射也叫路由系统,就是通过字符串的形式导入模块;通过字符串的形式去模块中寻找指定的函数,并执行,利用字符串的形式去对象(模块)中操作(查找、获取、删除、添加)成员,一种基于字符串的时间驱动。

 

获取:(getattr:获取或执行对象中的对象)

 1 class NameList():
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5 
 6     def Show(self):
 7         print("My name is %s and I‘m %d years old" %(self.name,self.age))
 8 
 9 obj = NameList("Adair",18)
10 # obj.Show()
11 UserInput=input(">>>")
12 print(getattr(obj,UserInput))
13 
14 >>>name
15 Adair
16 
17 >>>age
18 18
19 
20 >>>Show
21 __main__.NameList object at 0x000001F6CADEB358>>

 

 1 getattr 调用函数:
 2 class NameList():
 3     def __init__(self,name,age):
 4         self.name = name
 5         self.age = age
 6 
 7     def Show(self):
 8         print("My name is %s and I‘m %d years old" %(self.name,self.age))
 9 
10 obj = NameList("Adair",18)
11 # obj.Show()
12 UserInput=input(">>>")
13 Get = getattr(obj,UserInput)
14 Get()
15 
16 >>>Show
17 My name is Adair and Im 18 years old

 

查找:(hasattr:判断方式是否存在与对象中)

 1 class NameList():
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5 
 6     def Show(self):
 7         print("My name is %s and I‘m %d years old" %(self.name,self.age))
 8 
 9 obj = NameList("Adair",18)
10 UserInput=input(">>>")
11 print(hasattr(obj,UserInput))
12 
13 >>>name
14 True
15 
16 >>>Show
17 True
18 
19 >>>Adair
20 False

添加/修改(setattr

class NameList():
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def Show(self):
        print("My name is %s and I‘m %d years old" %(self.name,self.age))

obj = NameList("Adair",18)
InputKey=input(">>>")
InputValue=input(">>>")
New = setattr(obj,InputKey,InputValue)
print(getattr(obj,InputKey))

>>>salary
>>>100000
100000


>>>name
>>>xiaohei
xiaohei

 

删除:(delattr)

 1 class NameList():
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5 
 6     def Show(self):
 7         print("My name is %s and I‘m %d years old" %(self.name,self.age))
 8 
 9 obj = NameList("Adair",18)
10 UserInput=input(">>>")
11 delattr(obj,UserInput)
12 print(hasattr(obj,UserInput))
13 
14 >>>name
15 False

 

注:getattr,hasattr,setattr,delattr对模块的修改都在内存中进行,并不会影响文件中真实内容。

python 反射机制

标签:nbsp   method   and   bsp   style   .sh   show   def   int   

原文地址:https://www.cnblogs.com/Adairye/p/9643824.html


评论


亲,登录后才可以留言!