首页 > 解决方案 > 属性错误:函数没有属性“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”,当它被定义为“自动漫游者”时。

标签: pythonfunctionobjectattributeerror

解决方案


首先,您需要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)

推荐阅读