[英]Why does “from file import class work”, and not “import file”?
I made a class in a single file and it looks like below: 我在一个文件中制作了一个类,如下所示:
class Robot():
def __init__(self, name, desc, color, owner):
# initializes our robot
self.name = name
self.desc = desc
self.color = color
self.owner = owner
def drive_forward(self):
#simulates driving forward
print(self.name.title() + " is driving" + " forward " + str(self.duration)+ " milliseconds")
def drive_backwards(self):
print(self.name.title() + " is driving" + " backwards " + str(self.duration) + " milliseconds")
def turn_left(self):
print(self.name.title() + " is turning " + " left " + str(self.duration) + " milliseconds")
def turn_right(self):
print(self.name.title() + " is turning " + " right " + str(self.duration) + " milliseconds")
and I was trying to import this file to another file, so I can instantiate it and see how OOP works like. 并且我试图将此文件导入另一个文件,因此我可以实例化它,并查看OOP的工作方式。
And the other file that I was trying to import the class and instantiate looks like below: 我试图导入该类并实例化的另一个文件如下所示:
from robot_sample_class import Robot
my_robot = Robot("Nomad", "Autonomous rover", "Black", "JAY")
print("My robot is a " + my_robot.desc + " called " + my_robot.name)
my_robot.drive_forward()
my_robot.drive_backwards()
my_robot.turn_left()
my_robot.turn_right()
This code works well on the Python Shell; 这段代码在Python Shell上运行良好; however, if I just write 但是,如果我只是写
import "robot_sample_class" alone rather than "from robot_sample_class import Robot" 单独导入“ robot_sample_class”,而不是“从robot_sample_class导入Robot”
It doesn't work and it spits out an error message such as: 它不起作用,并显示一条错误消息,例如:
my_robot = Robot("Nomad", "Autonomous rover", "Black", "JAY") NameError: name 'Robot' is not defined my_robot =机器人(“游牧”,“自主漫游者”,“黑色”,“ JAY”)NameError:未定义名称“机器人”
Why is this the case? 为什么会这样呢? I thought importing the entire file will allow me to access everything in that file? 我以为导入整个文件将允许我访问该文件中的所有内容?
import robot_sample_class
means you need to write: 意味着您需要编写:
robot_sample_class.Robot(...)
If you want to import everything into the global namespace, use: 如果要将所有内容导入全局名称空间,请使用:
from robot_sample_class import *
Although this is not recommended for code that is meant to last. 尽管不建议将代码持久化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.