"Python3中有多个内部类吗?"

2024-04-19 07:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想这样做:

Robot.GyroController.getLatestMeasurement()

有办法吗? 更具体地说,我想这样做:

robot = Robot.__init__(arguments)
latesMeasurement = robot.GyroController.getLatestMeasurement()

这是有效的python吗?最重要的是,有可能吗?你知道吗

我要参加一个乐高比赛。我可以使用任何我想使用的编程语言,所以我想我应该写一个库来获得比现有库更好的抽象(也可以在我想进入tensorflow时练习python)

我有一门课叫机器人。该类通过引用机器人拥有的所有电机/传感器进行初始化。你知道吗

从那里,我想要一些子类(或者其他什么?)它可以控制电机,传感器,和做一些其他奇特的事情。你知道吗

每次我使用电机/传感器时,我都不必经过机器人(其中包含电机/传感器的引用),我想我可以这样做。你知道吗

另外,我来自OOP,仍在学习python,所以请注意,我打算尽可能地改进这个问题。请给我一个机会。你知道吗


Tags: inittensorflow机器人robot传感器子类事情arguments
1条回答
网友
1楼 · 发布于 2024-04-19 07:00:36

从我读到的,你想有一个机器人类,有多个电机类或类似的,也许这可以作为一个如何可以做到这一点的提示:

class Motor:
    def __init__(self, motor):
         self.motor = motor

    def go_slow(self):
         self.motor.setval = 100

    def go_fast(self):
         self.motor.setval = 255

class Robot:
    def ___init___(self, reference_motor1, reference_motor2):
        self.motor1 = Motor(reference_motor1)
        self.motor2 = Motor(reference_motor1)

    def go_straight_slow():
         self.motor1.go_slow()
         self.motor2.go_slow()

    def go_straight_fast():
         self.motor1.go_fast()
         self.motor2.go_fast()

下面是一个虚拟的例子,如果你想做面向对象的工作,你的代码可能是什么样子的。你知道吗

编辑: 假设你已经得到了“MotorController”这个类

 class MotorController:
      def __init__(self):
          pass

      def goStraight():
          pass


 class Robot:
        def ___init___(self):
            self.motor_controllers = [] #List for storing all motors

        def add_motor_reference(self, reference):
            self.motor_controllers.append(MotorController(reference)) 
            #Appends new motors to the list

        def go_straight(self):
            for motor_controller in self.motor_controllers:
                motor_controller.goStraight()
            #Executes for the "goStraight" function on every motor in the list

编辑: 如果要在类的构造函数中添加马达,可以执行以下操作:

 class Robot:
        def ___init___(self, *args):
            self.motor_controllers = [] #List for storing all motors
            for motor in args:
                self.motor_controllers.append(MotorController(motor))
            #Here every motor reference you pass will be automatically added in the list of motor controllers.

相关问题 更多 >