I'm working on writing my first Python class. Being the java programmer that I am, I have something like this:
#class1.py
class class1:
def __init__(self):
#Do stuff here
And in my current script:
import class1
object = class1()
I'm getting a Name Error: name 'class1' is not defined
I've also tried this, with no luck:
import class1
object = class1.class1()
The error I get here is AttributeError: 'module' object has no attribute 'class1'
What am I doing wrong?
asked Jan 21, 2013 at 17:13
PearsonArtPhoto
39.9k17 gold badges118 silver badges147 bronze badges
2 Answers 2
Python import is by module and then by the contents of the module, so for your class1.py it becomes:
from class1 import class1
answered Jan 21, 2013 at 17:16
Max Fellows
3923 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
PearsonArtPhoto
Wow, that simple... Thanks!
John Y
Well, this works, but it doesn't explain why
class1.class1() can't be used as a constructor when the class1 module has been successfully imported.Stuart Robertson
@JohnY That would have worked but it says in the comments under his question that his file name is tle.py. So they were importing the wrong module. Strange why there was no ImportError in that case though.
John Y
@StuartRobertson: No, the file name
tle.py in the comments was just to confirm that the OP didn't just happen to pick a module name conflicting with something else. For purposes of the question, the module is the file class1.py, containing the class definition class1, as given in the text of the question. And ordinarily, you should be able to create an instance of class1 by first importing the class1 module, and then calling class1.class1().In Python you import the modules. For class1.py file you can use:
from class1 import class1
Or if you have more than one....
from class1 import *
answered Jan 21, 2013 at 17:20
Sudip Kafle
4,4115 gold badges38 silver badges49 bronze badges
Comments
lang-py
tle.py/tle. Not sure why it makes a difference...