首页 > 技术文章 > 反射

chenadong 2018-08-25 23:53 原文

import sys

height = 1


class Person(object):
	def __init__(self):
		pass

	@staticmethod
	def height():
		print "1.80"

	@staticmethod
	def weigh():
		print "120"


print getattr(Person, "height")      # 在类中的使用
getattr(Person, "height")()

print getattr(sys.modules[__name__], "height")        # 获取当前模块内的一个全局变量
getattr(sys.modules[__name__].Person, "height")()     
# 在当前模块的指定类中的方法,如果是其他指定模块,__name__
# 更换成对应的模块名称,注意要加上双引号;

  

<function height at 0x00000000037F8668>      # 返回方法地址
1.80            # 执行了方法
1               
1.80

推荐阅读