0
点赞
收藏
分享

微信扫一扫

python反射总结, 写socket时很好用,短小精悍

思考的鸿毛 2022-01-20 阅读 54

在python 2.7中测试通过
写socket的时候, 经常要使用到反射, 这里总结一下使用方式

  1. 类型1. 执行全局的方法, 可以直接在globals()中找到
  2. 类型2. 执行实例的方法,
    2.1 实例已经存在: 可以通过getattr(instacne, name)来拿到对应的属性(方法)来执行
    2.2 实例不存在: 可以在globals()中通过类名 找到该对象并初始化, 然后上面的规则

类型1

# 类型1, 全局方法
def print_hello(_h, _w):
	print _h,
	print _w


method_name = 'print_hello'
args = ['hello', 'world']
globals()[method_name](*args)

类型2

# 类型2, 实例方法
# 2.1 在内部
class A(object):
	def __init__(self):
		pass

	def print_hello(self, _h, _w):
		print _h,
		print _w

	def run(self):
		getattr(self, method_name)(*args)


a = A()
a.run()

# 2.2 在外部
getattr(a, method_name)(*args)


# 2.3 先实例化, 再执行
class_name = 'A'
class_init_args = []
a_instance = globals()[class_name](*class_init_args)
getattr(a_instance, method_name)(*args)

举报

相关推荐

0 条评论