Reputation: 626
I'm getting a little confused about importing methods from another file.
I'm writing a Python script that imports from python-automata
. I've downloaded the file and in my ../Python/
directory, I have DFA.py
and myfile.py
stored.
In myfile.py
I have this written on top:
import DFA
As I'm following what's written in the python tutorial, I assume that in myfile.py
I can use any method defined in DFA.py
. That file has a method called __init__
which takes in 5 arguments and initializes a DFA
. Then I write this in myfile.py
:
DFA.__init__(states, alphabet, delta(states, alphabet), start, accepts)
Where states, alphabet, delta, start, and accepts are all basic lists/functions that I have initialized in myfile.py.
But then when I try to run myfile.py, I get this error:
Traceback (most recent call last):
File "myfile.py", line 21, in <module>
DFA.__init__(states, alphabet, delta(states, alphabet), start, accepts)
TypeError: module.__init__() takes at most 2 arguments (5 given)
I'm not sure why it says it takes 2 arguments, when DFA.py
defines it as taking in 5 arguments. In DFA.py
, I see:
class DFA:
def __init__(self, states, alphabet, delta, start, accepts):
...
It seems like a similar errors I encountered earlier (see Python import issue and Python classes and __init__ method) but I don't think that I need to deal with inheritance here.
Upvotes: 0
Views: 3908
Reputation: 108
When you put in DFA.__init__()
, you're calling the __init__
method for the entire module (I don't even know what that is defined as). You should use DFA.DFA.__init__()
, which refers to the __init__
method of the DFA
class within DFA.py
, or use:
from DFA import *
DFA.__init__()
Upvotes: 0
Reputation: 2557
You're importing DFA
as a module, but you want to import the class within it instead. Try:
from DFA import DFA
You can then implicitly call __init__
by calling the constructor on your DFA
class:
DFA(states, alphabet, delta(states, alphabet), start, accepts)
# ^ this calls __init__ on DFA
Upvotes: 4
Reputation:
from DFA import DFA
a = DFA(states, alphabet, delta(states, alphabet), start, accepts)
EDIT: methods named __xx__
are not meant to be called directly.
Some reading: http://docs.python.org/tutorial/classes.html
Upvotes: 5