如何在python中动态加载不同位置的类并获取类中的方法名称
题
我有wriiten简单的class.py文件,其中有类 班级雇员:
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self,salary):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
现在我已经编写了另一个脚本来导入文件并获取类中的方法,但我无法获取方法
import inspect
import sys
pat="E://pythonscripts"
sys.path.append(pat)
#pat="E:/pythonscripts/Simpleclass"
__import__('Simpleclass', globals={})
for name, method in inspect.getmembers('Simpleclass', inspect.ismethod):
print name
(args, varargs, varkw, defaults) = inspect.getargspec(method)
for arg in args:
print arg
运行inspect脚本时,我收到以下错误
Traceback (most recent call last):
File "C:/Python27/stack.py", line 9, in <module>
for name, method in inspect.getmembers(Employee, inspect.ismethod):
NameError: name 'Employee' is not defined
解决方案
添加路径的 employee.py
模块在 sys.path
import sys
sys.path.append(<directory of employee.py module>)
对于导入动态模块使用 __import__
__import__('employee', globals={})
或
您可以使用 inspect
对于introspecting python类
import inspect
for name, method in inspect.getmembers(<your class>, inspect.ismethod):
print name
(args, varargs, varkw, defaults) = inspect.getargspec(method)
for arg in args:
print arg
不隶属于 StackOverflow