-1

I am trying to call a module with mod = importlib.import_module(str) from Sample2.py and the module which

I am calling is PlayAround_Play.py it is working fine when it contains only a function . If I included a class to that function

It is not working fine. Getting error as TypeError: this constructor takes no arguments

code in sample2.py

import importlib
def calling():
      str="PlayAround_Play" 
      a=10
      b=20
      c=30
      mod = importlib.import_module(str)
      getattr(mod,str)(a, b, c)    

calling()

code in PlayAround_Play.py

class PlayAround_Play():
        def PlayAround_Play(self, a, b, c):
              d=a+b+c
              print d

can u guys show me a solution how to call that class by using importlib

Prophet
  • 32,350
  • 22
  • 54
  • 79
somesh
  • 77
  • 1
  • 2
  • 9
  • 1
    That's because the constructor method is always named `__init__`, it isn't named after the class... How do you know about importlib and getattr but don't know basics about python classes? – l4mpi Nov 06 '13 at 09:23
  • ... Well, after reading your other questions it's pretty clear that you don't know anything about python and only got this code from other people as answers to your previous question. Please get a basic understanding of the language by reading the [python tutorial](http://docs.python.org/2/tutorial/) before asking further questions. – l4mpi Nov 06 '13 at 09:27
  • tried with different names also getting same error.. – somesh Nov 06 '13 at 09:30
  • yes.. i dont know about python language learning now – somesh Nov 06 '13 at 09:32

1 Answers1

1

You're calling your class incorrectly, correct way:

inst = getattr(mod, strs)()   #creates an instance of the class
inst.PlayAround_Play(a, b, c) #call `PlayAround_Play` method on the instance.

Output:

60

To make your code work fine define __init__ in your class:

class PlayAround_Play():

    def __init__(self, a, b, c):
        d = a+b+c
        print d

Now:

getattr(mod, strs)(a, b, c)
#prints 60

Read:

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • That seems like a bad use of `__init__`, using a print statement instead of initialization. –  Nov 06 '13 at 09:40