![](/img/trans.png)
[英]Is there a way in python that if i create a .py file and then will import in a different .py file which has catch clauses for all the exceptions,
[英]Create Python object from different .py file
在一个文件中,我创建了一个名为Robot的类,但是当我尝试在另一个文件中创建该类的对象时,它说:'module'对象没有属性'Robot'
main.py
import robot as rob
robot=rob.Robot()
robot.py
class Robot(object):
def __init__(self):
return 0
def otherFunctions():
return 0
它说:“模块”对象没有属性“机器人”。 我在哪里犯错?
代码的编写方式是正确的(除非您为简明起见而进行了删除)
import
,Python会检查sys.path
中的导入位置,然后导入它可以找到的第一个 robot
。
解决此问题的几种方法:
import robot
print robot.__file__
在robot.py中
print("hello!")
import sys
sys.path.insert('/path/to/correct/robot/')
import robot
您的robot.py文件中的语法似乎不正确。 您可以通过将robot.py文件更改为以下形式,以最直接的方式纠正错误:
class Robot(object):
def __init__(self):
pass
def other_functions(self):
pass
请注意,我为other_functions
函数使用了蛇形外壳。 不要在Python中使用camelCasing。 这不是惯用语。 另外,我在other_functions
添加了一个self
参数,因此,如果您尝试从Robot
实例中调用它,则不会出现TypeError
。
另外,除非您的代码确实像您呈现的那样简单,否则错误可能是循环导入引起的。 确保在它们有机会完全执行之前,不要试图彼此导入这两个模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.