0

I have wriiten the Simple class .py file which has the class class Employee:

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

and now i have written the another script to import the file and get the methods in the class but i am not able to fetch the methods

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

when running the inspect script i am getting the following error

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
Nilesh
  • 20,521
  • 16
  • 92
  • 148

1 Answers1

0

Add path of the employee.py module in sys.path

import sys
sys.path.append(<directory of employee.py module>)

For import dynamic module use __import__

__import__('employee', globals={})

OR

importlib

You can use inspect for introspecting python class

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
Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • 1
    But this doesnot work if it is in different path means emplyee class in one path and inspect file is in another path – user3824589 Jul 30 '14 at 08:46
  • I have wriiteen the following codeimport sys pat="E:/pythonscripts" sys.path.append(pat) #pat="E:/pythonscripts/Simpleclass" __import__(Simpleclass, globals={}) but it is throwing the error as name 'Simpleclass' is not defined So please can you tell wat is the mistake – user3824589 Jul 30 '14 at 08:54
  • Will you please update your question with latest code? – Nilesh Jul 30 '14 at 08:57
  • You can use `employee = __import__('employee')` to import it as a module. Use `employee.Employee` to access that class. – Jochen Ritzel Jul 30 '14 at 09:20