Python----面向对象---反射

一、引子,想根据用户的输入来判断输出的属性

代码如下:

 1 class People:
 2     def __init__(self, name, age):
 3         self.name = name
 4         self.age = age
 5 
 6     def talk(self):
 7         print('%s is talking ' % self.name)
 8 
 9 obj = People('alex', 29)
10 
11 # print(obj.name)  # obj.__dict__['name']
12 # print(obj.talk)
13 
14 choice = input('>>:')  # choice = 'name'
15 print(obj.choice)  # print(obj.'name')
16 
17 结果为:
18 
19 >>:add
20 Traceback (most recent call last):
21   File "C:/Users/xudachen/PycharmProjects/Python全栈开发/第三模块/面向对象/23 反射.py", line 17, in <module>
22     print(obj.choice)  # print(obj.'name')
23 AttributeError: 'People' object has no attribute 'choice'

结果报错,是因为方式错误,name为字符串,所以说报错,那有没有方法实现呢,这就用到反射方法,如下:

二、通过字符串映射到对象的属性

1、查询是否有某个属性

 1 class People:
 2     def __init__(self, name, age):
 3         self.name = name
 4         self.age = age
 5 
 6     def talk(self):
 7         print('%s is talking ' % self.name)
 8 
 9 obj = People('alex', 29)
10 
11 # print(obj.name)  # obj.__dict__['name']
12 # print(obj.talk)
13 
14 # choice = input('>>:')  # choice = 'name'
15 # print(obj.choice)  # print(obj.'name')
16 
17 print(hasattr(obj, 'name'))  # obj.name # obj.__dict__['name']
18 print(hasattr(obj, 'talk'))  # obj.talk
19 
20 结果为:
21 True
22 True

True说明有这个属性

2、获取某个属性

1 print(getattr(obj, 'name'))
2 
3 结果为:
4 
5 alex

但是如果没有某个属性,就会报错

1 print(getattr(obj, 'name123'))
2 
3 结果为:
4 
5 Traceback (most recent call last):
6   File "C:/Users/xudachen/PycharmProjects/Python全栈开发/第三模块/面向对象/23 反射.py", line 22, in <module>
7     print(getattr(obj, 'name123'))
8 AttributeError: 'People' object has no attribute 'name123'

如果不让让他报错,可以加一个default参数,例如None

1 print(getattr(obj, 'name123', None))
2 
3 结果为;
4 
5 None

获取函数属性;

1 print(getattr(obj, 'talk', None))
2 
3 结果为;
4 
5 <bound method People.talk of <__main__.People object at 0x0000028F3FD2B358>>

3、设置某个属性

1 setattr(obj, 'sex', 'male')  # obj.sex = 'male'
2 print(obj.sex)
3 
4 结果为;
5 
6 male

4、删除某个属性

1 delattr(obj, 'age')  # del obj.age
2 print(obj.__dict__)
3 
4 结果为:
5 
6 {'name': 'alex'}

5、对类来说,是类似的,也可以获取某个属性,例如数据属性和函数属性

1 print(getattr(People, 'country'))  # People.country
2 
3 结果为:
4 
5 China
原文地址:https://www.cnblogs.com/xudachen/p/8622989.html