• 主页
  • 相册
  • 随笔
  • 目录
  • 存档
Total 244
Search AboutMe

  • 主页
  • 相册
  • 随笔
  • 目录
  • 存档

Python反射

2020-05-24

1. 概述

反射(reflection),或称“自省”(introspection)是指Python脚本可以得到一个对象的类型、class、属性、方法等信息。 在某些时候,需要执行对象的某个方法,或是需要给对象的某个字段赋值,而方法名或是字段名在编写代码时并不能确定,需要通过字符串参数传递的形式输入。

下列函数实现了反射:type(), isinstance(), issubclass(), callable(), dir(), getattr()


Reflection refers to the ability for code to be able to examine attributes about objects that might be passed as parameters to a function

2. 例子:“泛型反转”

在python里用“泛型”这个词怪怪的…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Python program to illustrate reflection 
def reverse(seq):
SeqType = type(seq)
emptySeq = SeqType()

if seq == emptySeq:
return emptySeq

restrev = reverse(seq[1:])
first = seq[0:1]

# Combine the result
result = restrev + first

return result

# Driver code
print(reverse([1, 2, 3, 4])) # [4,3,2,1]
print(reverse("HELLO")) # OLLEH

3. 例子:case的替代

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
class User:
def __init__(self,name):
self.name = name

def eat(self):
print('%s 正在吃夜宵 ...'%self.name)

def run(self):
print('%s 正在跑步中 ...'%self.name)

# 场景: 当用户在操作时,面对用户不同的操作就需要调用不同的函数
# 如果用if,elif语句的话,会存在一个问题,当用户有500个不同的操作,
# 就需要写500次if,elif。这样就会出现代码重复率高,而且还不易维护
# 这时候反射就出现了,通过字符串映射对象或方法

# 实例化一个对象: 胖毛
c = User('胖毛')

# 用户输入指令
choose = input('>>>:')

# 通过hasattr判断属性/方法是否存在
if hasattr(c,choose):
# 存在,用一个func接收
func = getattr(c,choose)
# 通过类型判断是属性还是方法
if type(func) == str:
print(func)
else:
func()
else:
print('操作有误,请重新输入')

4. 参考

  • Python/反射 - 维基教科书,自由的教学读本
  • reflection in Python - GeeksforGeeks
  • 「反射」 Python中的神器 - 简书
  • Program Language
  • Python
  • Advanced
Python数据模型
Flask浅析-1
  1. 1. 1. 概述
  2. 2. 2. 例子:“泛型反转”
  3. 3. 3. 例子:case的替代
  4. 4. 4. 参考
© 2024 何决云 载入天数...