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

在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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值