Python “为什么?”;“从文件导入类工作”中;,而不是",;导入文件";?
我在一个文件中创建了一个类,如下所示:Python “为什么?”;“从文件导入类工作”中;,而不是",;导入文件";?,python,class,import,Python,Class,Import,我在一个文件中创建了一个类,如下所示: 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):
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")
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()
我正试图将这个文件导入到另一个文件,这样我就可以
实例化它,看看OOP是如何工作的
我试图导入类并实例化的另一个文件如下所示:
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")
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()
这段代码在pythonshell上运行良好;然而,如果我只是写
单独导入“robot\u sample\u class”,而不是“从robot\u sample\u class导入robot”
它不工作,并会弹出一条错误消息,如:
my_robot=机器人(“游牧民”、“自主漫游者”、“黑色”、“杰伊”)
NameError:未定义名称“Robot”
为什么会这样?我想导入整个文件将允许我
访问该文件中的所有内容
import robot_sample_class
意味着你需要写:
robot_sample_class.Robot(...)
如果要将所有内容导入全局命名空间,请使用:
from robot_sample_class import *
虽然这不建议用于持久的代码
意味着你需要写:
robot_sample_class.Robot(...)
如果要将所有内容导入全局命名空间,请使用:
from robot_sample_class import *
虽然这不建议用于持久的代码