名称错误:使用类时未定义名称'Robot'

  • 本文关键字:未定义 Robot 错误 python
  • 更新时间 :
  • 英文 :


我正在读一本关于Python的书,我一直在学习类。

一位作者建议在一个名为robot_sample_class.py的单独文件中创建一个类,代码如下:

class Robot():
"""
A simple robot class
This multi-line comment is a good place
to provide the description of what the class
is.
"""
# define the initiating function.
# speed = value between 0 and 255
# duration = value in milliseconds
def __init__(self, name, desc, color, owner, speed = 125, duration = 100):
#initializes our robot
self.name = name
self.desc = desc
self.color = color
self.owner = owner
self.speed = speed
self.duration = duration
def drive_forward(self):
#simulates driving forward
print(self.name.title() + " is driving" + " forward " + str(self.duration) + " milliseconds")
def drive_backward(self):
#simulates drawing backward
print(self.name.title() + " is driving" + " backward " + str(self.duration) + " milliseconds")
def turn_left(self):
#simulates turning left
print(self.name.title() + " is turning" + " right " + str(self.duration) + " milliseconds")
def turn_right(self):
#simulates turning right
print(self.name.title() + " is turning" + " left " + str(self.duration) + " milliseconds")
def set_speed(self, speed):
#sets the speed of the motors
self.speed = speed
print("the motor speed is now " + str(self.speed))
def set_duration(self, duration):
#sets duration of travel
self.duration = duration
print("the duration is now " + str(self.duration))

然后,创建一个新文件,robot_sample.py,代码为:

import robot_sample_class
my_robot = Robot("Nomad", "Autonomous rover", "black", "Jeff Cicolani")
print("My robot is a " + my_robot.desc + " called " + my_robot.name)
my_robot.drive_forward()
my_robot.drive_backward()
my_robot.turn_left()
my_robot.turn_right()
my_robot.set_speed(255)
my_robot.set_duration(1000)

尽管它在书中运行得很完美,但我总是会遇到一个错误:

Traceback (most recent call last):
File "C:UsersVladDesktoprobot_sample.py", line 2, in <module>
my_robot = Robot("Nomad", "Autonomous rover", "black", "Jeff Cicolani")
NameError: name 'Robot' is not defined

我已经彻底检查了代码,不知道我还应该做什么。也许问题甚至与代码无关。

您需要专门从robot_sample_class.py导入Robot类。将您的进口声明更改为以下内容:

from robot_sample_class import Robot

编辑:或者,您可以通过以下命名空间限定Robot对象来实例化它:

my_robot = robot_sample_class.Robot("Nomad", "Autonomous rover", "black", "Jeff Cicolani")

最新更新