【发布时间】:2018-12-09 15:13:11
【问题描述】:
我正在尝试书中的代码:使用 Raspberry Pi 和 Arduino 开始机器人技术:使用 Python 和 OpenCV。在第一章中,作者让我们输入代码来模拟控制机器人。在python中,创建了一个名为robot_sample_class.py的文件,代码为:
class Robot():
"""
A simple robot class
This multi-line comment is a good place
to provide a 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):
# initiates 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 driving 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))'
然后,我创建了一个名为 robots_sample.py 的文件,代码如下:
import robot_sample_class
def my_robot(): Robot("Nomad", "Autonomous rover","black", "Cecil")
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)
当我运行robot_sample.py 时,我收到一条错误消息:print("My robot is a " + my_robot.desc + " called " + my_robot.name). AttributeError:函数对象没有属性“desc”。
我不明白为什么该函数没有属性“desc”,当它被定义为“自动漫游车”时。
【问题讨论】:
-
尝试
my_robot = Robot(...)然后my_robot.desc应该可用 -
谢谢,这是我以前的,但它会带来错误: NameError: name 'Robot' is not defined。所以,如果我根据你的建议更改它,我只会收到一个新错误。
标签: python function object attributeerror