In one file I create a class called Robot, but when I try to create an object of that class in another file it says:'module' object has no attribute 'Robot'
main.py
import robot as rob
robot=rob.Robot()
robot.py
class Robot(object):
def __init__(self):
return 0
def otherFunctions():
return 0
And it says: 'module' object has no attribute 'Robot'. Where I am making a mistake?
The way your code is written is correct (barring removal you've presumably made for conciseness)
When you import
, Python checks sys.path
for importing locations, and imports the first robot
it can find.
A couple ways to solve this:
import robot
print robot.__file__
in robot.py
print("hello!")
import sys
sys.path.insert('/path/to/correct/robot/')
import robot
It seems like the syntax in your robot.py file is not correct. You can correct the errors in the most direct way by changing your robot.py file to look like this:
class Robot(object):
def __init__(self):
pass
def other_functions(self):
pass
Note that I used snake casing for the other_functions
function. Don't use camelCasing in Python. It's not idiomatic. Also, I added a self
argument to other_functions
so you won't get a TypeError
if you try to invoke it off of a Robot
instance.
Also, unless your code is truly as simple as you present it, the error might be coming from a circular import. Make sure you're not trying to import the two modules from each other before they've had a chance to fully execute.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.