如何动态加载不同位置的类并在python中获取类中的方法名称

时间:2014-07-30 08:32:47

标签: python inspect

我已经使用了具有该类的Simple类.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

运行检查脚本时出现以下错误

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

1 个答案:

答案 0 :(得分:0)

employee.py

中添加sys.path模块的路径
import sys
sys.path.append(<directory of employee.py module>)

对于导入动态模块,请使用__import__

__import__('employee', globals={})

importlib

您可以使用inspect进行内省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