python - 属性错误:函数没有属性“desc”
问题描述
我正在尝试书中的代码:使用 Raspberry Pi 和 Arduino 开始机器人学:使用 Python 和 OpenCV。在第一章中,作者让我们输入代码来模拟控制机器人。在 python 中,创建了一个名为 robots_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)
当我运行 robots_sample.py 时,我收到一条错误消息:print("My robot is a " + my_robot.desc + " called " + my_robot.name). AttributeError:函数对象没有属性“desc”。
我不明白为什么该函数没有属性“desc”,当它被定义为“自动漫游者”时。
解决方案
首先,您需要Robot
从模块中导入类。其次,你应该实例化它(创建这个类的一个变量)。之后,您可以使用它:
from robot_sample_class import Robot
my_robot = Robot("Nomad", "Autonomous rover","black", "Luke Periard")
print("My robot is a " + my_robot.desc + " called " + my_robot.name)
推荐阅读
- react-native - 排毒:“找不到 UI 元素。” 尝试滚动 FlatList 时
- performance - 将 DiffUtil 与 LIveData + Room 数据库一起使用的最佳方法?
- c++ - 为什么破坏后不提示“double free”
- dart - 以异步方式使用 .map()、.where() 等迭代助手?
- cucumber-jvm - 具有两个具有奇怪网络定位器问题的单独场景的功能文件
- bash - 在bash中的X个字符后切断变量
- image - 如何在 TYPO3 中处理图像宽度/高度?
- angular - 通过代码切换 Angular 的 cdkDrag 拖放
- mysql - FireDAC GetTableNames MySQL
- ios - 为什么 autosize collectoinviewcell 不起作用?