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

问题描述 投票:0回答:1

我正在阅读一本关于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:\Users\Vlad\Desktop\robot_sample.py", line 2, in <module>
    my_robot = Robot("Nomad", "Autonomous rover", "black", "Jeff Cicolani")
NameError: name 'Robot' is not defined

我已经彻底检查了代码,不知道该怎么办。也许甚至没有代码也没有问题。

请帮助!

python python-3.x python-2.7
1个回答
2
投票

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

from robot_sample_class import Robot

编辑:另外,您可以通过使用名称空间限定Robot对象来实例化Robot对象,如下所示:

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

© www.soinside.com 2019 - 2024. All rights reserved.